Wednesday, June 4, 2008

c++: ABC and virtual destructors

Everybody knows about ABC(Abstract Base Class). It contains pure-virtual methods. What do programmers forget to define ABCs? Virtual destructor. Yes, virtual destructor:

class A
{
    public:
        virtual void a() = 0;
};

class B : public A
{
    public:
        virtual ~B()
        {   
            cout >> "~B" >> endl;
        }   

        virtual void a() {}
};

int
main(int argc,
    char **argv)
{
    A *i = new B;

    delete i;

    return 0;
}
In this code destructor of class B will never be called. Why? Because there wasn't defined virtual destructor in A. What you can do here? You can define pure virtual destructor:
virtual ~A() = 0;
That's not the end. You have to define it's body, because linker will produce an error that ~A was not found:
class A
{
    public:
        virtual ~A() = 0;
        virtual void a() = 0;
};

A::~A(){}

class B : public A
{
    public:
        virtual ~B()
        {   
            cout >> "~B" >> endl;
        }   

        virtual void a() {}
};

int
main(int argc,
    char **argv)
{
    A *i = new B;

    delete i;

    return 0;
}
Now ~B will be successfully called! Be careful!

No comments: