Does destructor of derived class remove virtual table?

M

Martin Koller

Hi list,

I have a small example which gives me "pure virtual function called".

I'm calling a virtual function in the destructor of the base class, where
the pointer used is effectively pointing to a derived class, but the whole
thing is in the process of being destroyed.

Interesting for me is also, that I get the same error if I call b->isA() in
the constructor of Base.

I just wanted to know, if this behavior is correct in C++ terms or is it a
compiler issue ? (using gcc-2.3.2 on Linux)

(Please CC me on mail)

#include <iostream>

class Base
{
public:
Base(Base *x) { b = x; };
virtual ~Base()
{
b->isA();
};

virtual int isA() = 0;

private:
Base *b;
};

class Derived : public Base
{
public:
Derived() : Base(this) { std::cerr << isA() << std::endl; };

virtual int isA() { return 1; }
};


main()
{
Derived *d = new Derived();

delete d;
}

Thanks,

Martin
 
R

Rolf Magnus

Martin said:
Hi list,

I have a small example which gives me "pure virtual function called".

I'm calling a virtual function in the destructor of the base class,
where the pointer used is effectively pointing to a derived class, but
the whole thing is in the process of being destroyed.

In the destructor of the base class, the derived part of the objects is
already destroyed, so it isn't anymore an instance of the derived
class.
Interesting for me is also, that I get the same error if I call
b->isA() in the constructor of Base.

Same principle. In the base class constructor, the derived part of the
object does not yet exist. Therefore a polymorphic call won't call the
derived implementation of the virtual function.
I just wanted to know, if this behavior is correct in C++ terms or is
it a compiler issue ? (using gcc-2.3.2 on Linux)

It is correct.
 
D

David Harmon

I have a small example which gives me "pure virtual function called".

I'm calling a virtual function in the destructor of the base class,

See also the topic "[23.3] When my base class's constructor calls a
virtual function on its this object, why doesn't my derived class's
override of that virtual function get invoked?" in Marshall Cline's C++
FAQ. The remarks regarding constructors mostly apply for the same
reasons to destructors. You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top