This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Subtle problem with virtual keyword that can mislead the unwary...



I'm not really sure this is a bug, but the visible evidence of a
programming mistake doesn't do anything to point me at the error.
Here's a simple program with a mistake:

    #include <stdio.h>

    class A {
    public:
      virtual int mf(int) = 0;
      virtual ~A();
    };

    class B : public A {
    public:
      virtual int mf(int i) {
	fprintf(stderr, "B::mf() called.\n");
	return i;
      }
      ~B();
    };

    A::~A() {
      fprintf(stderr, "A destructor called.\n");
    }

    int main(int argc, char **argv) {
      B *a;

      a = new B;
      a->mf(1);
      delete a;
    }

egcs (1.00) reports:

    Undefined                       first referenced
     symbol                             in file
    B virtual table                     /var/tmp/cca000C01.o

g++ 2.8.0 reports the same thing, only uglier:

    Undefined                       first referenced
     symbol                             in file
    _vt.1B                              /var/tmp/cca000C_1.o

Now, I suspect all the C++ experts reading this are way ahead of me,
thinking, "The problem's obvious. He forgot to declare B's destructor
virtual."  Sure enough, adding the "virtual" keyword to the
declaration of B::~B() cures the error.

The question I have is: Can't the compiler be a little more helpful
here?  Can it at least warn the programmer that the destructor is
declared virtual in A but not in its subclass?  (Compiling with -Wall
doesn't cause a peep from the compiler.)

-- 
Skip Montanaro (montanaro@crd.ge.com, 518 387 6792)
Speaking only for myself, not GE.  (They make me say that...)


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]