Ale
Ale

Reputation: 1

How to use destructor with inheritance?

Let's say I have objects: B Ob1, C Ob2. I want to build a destructor for classes B and C, but I'm not sure how to destroy B.bb and C.cc and how to acces them. Also, is there a way I am able to do this without making classes friends of class A?

class A
{
protected:
   int a, aa;
public:
   A();
   A(int a, int aa);
   ~A();
   friend class B;
   friend class C;
};
class B
{
protected:
   int b;
   A bb;
public:
   B();
   A(int b, A bb);
   ~B();
};
class C: class B
{
private:
   int c;
   A cc;
public:
   C();
   C(int c, A cc);
   ~C();
  };

Upvotes: 0

Views: 153

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148860

As soon as you use inheritance, the destructor should be virtual:

class B
{
    ...
public:
   B();
   A(int b, A bb);
   virtual ~B();
};

The rationale, is that as soon as you will use polymorphism and pointers bad things could happen:

B *obj = new C();
...
delete obj;       // if ~B is not virtual, you never call C destructor...

Upvotes: 0

You don't. They are destroyed automatically. friends are not needed for this.

Upvotes: 4

Related Questions