Bug in g++: optimizes away virtual function of local class

Glenn Horton-Smith gas@awa.tohoku.ac.jp
Mon Apr 10 19:09:00 GMT 2000


Greetings,
	If one defines a class within a block of code, and it contains 
a virtual member function which is never referenced in the surrounding 
code, the compiler optimizes away the function, even if it is a
virtual function overriding a virtual function of a parent class.
This can cause problems:  specifically, correct code that compiles and 
links okay with -O0 will lack the necessary function when compiled
with -O1.  See below.
					-Glenn.

////////////////////////////////////////////////////////////////
// Code to demonstrate a compiler bug that occurs due to optimizing
// away functions defined for classes defined local to a block of code.
// The program will not link if compiled with -O1 (or -O2) in gcc 2.95.2.
// All is well if compiled with -O0.
// (The compiler really should not eliminate virtual member functions.)
//    -Glenn Horton-Smith 2000.04.10
#include <iostream>

class TV1 {
public:
  virtual void virtfunc(void) = 0;
  void call_virtfunc(void);
};

int main(int argc, char **argv)
{
  class TV2 : public TV1 {
  public:
    void virtfunc(void) { cout << "TV2::virtfunc called" << endl; }
    // virtfunc will be inappropriately optimized away by gcc 2.95.2 and 2.95.1
    // if -O1 or -O2 is used, but will compile, link and run fine with -O0
  } tv2;

  tv2.call_virtfunc();

  return 0;
}

void TV1::call_virtfunc(void)
{
  virtfunc();
}
////////////////////////////////////////////////////////////////



More information about the Gcc-bugs mailing list