1

I want to inherit from class A, but A's destructor is not virtual and I cannot modify A's definition. How to avoid the following case?

struct A
{
    A()
        : a(new char[8])
    {}

    ~A()
    {
        delete[] a;
    }

    char* a;
}

struct B : A
{
    B()
        : A(), b(new char[8])
    {}

    ~B()
    {
        delete[] b;
    }

    char* b;
};

int main()
{
    A* p_a = new B;
    delete p_a; // How to avoid such a dangerous deletion?
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
xmllmx
  • 39,765
  • 26
  • 162
  • 323

3 Answers3

8

If the base class doesn't have a virtual destructor and you can't modify the class definition, you're pretty much out of luck. As a general rule of thumb, you probably shouldn't use public inheritance with a base class that doesn't have a virtual destructor.

Maybe you can try using composition instead of inheritance? Place an instance of A in B, and provide public member functions that wrap calls to member functions of A.

Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
1

You can use struct B : private A so that A is an inaccessible base of B.

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
0

Just make the A a data member instead of a base class.


By the way, the classes violate the rule of three, which is an invitation to disaster. What if an instance is copied. Better use standard library containers instead of explicit new and delete.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • @YuanWen: "Data member" is pretty fundamental. You're asking for sample code of declaring a variable. You need a textbook. The SO C++ [book list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) can help. – Cheers and hth. - Alf Aug 19 '16 at 11:48