Reputation: 16158
I read that destructors can't be shared, is this true?
I have a base class with several subclasses and the destructor of those subclasses does not change. This would result in some duplicated code.
Is it possible to share the destructor? If not how would I avoid duplicated code in those destructors?
Class A{
public:
~A() {
//do something
}
};
class B: public A{
};
class C: public A{
};
class D: public A{
};
Now I want B
, C
, and D
to have the same destructor as A
.
Upvotes: 0
Views: 76
Reputation: 1155
From your example the easiest thing to do is:
class A
{
public:
virtual ~A()
{
// Do stuff
}
}
Upvotes: 1
Reputation: 6387
If you don't implement a descructor in the inheriting class, a basic one will be generated that will simply call the base class destructor. So it is not shared, but the result is the same.
Upvotes: 1
Reputation: 283793
Every class's destructor automatically calls the destructor for all subobjects, including base class subobjects. So you can share behavior of the destructor by putting it in a base or member destructor. Of course, the derived class still gets its own destructor, but in most cases the compiler-generated one (which does nothing besides the mandatory calls to subobject destructors) is enough.
Upvotes: 2