#define CLASS(ID) class ID{ \
public: \
ID(int) { cout<<#ID <<"\tconstructor"<<endl; } \
~ID(){cout<<#ID<<"\tDestroyed "<<endl;} \
};
CLASS(Base);
CLASS(Member);
class Derived : public Base {
public:
Member *mem;
Derived(int x) : Base(1) {
cout<<"Derived constructor"<<endl;
mem=new Member(2);
}
~Derived()
{
cout<<"Derived Destroyed"<<endl;
delete mem;
}
};
int main(int argc, char** argv) {
Derived * der=new Derived(1);
cout<<"****"<<endl;
delete der;
}
The output for this is:
Derived constructor
Member constructor
****
Derived Destroyed
Member Destroyed
Base Destroyed
In the second version :
class Derived : public Base {
public:
Member *mem;
Derived(int x) : Base(1) {
cout<<"Derived constructor"<<endl;
}
~Derived()
{
cout<<"Derived Destroyed"<<endl;
delete mem;
}
};
Why in the first version the Base constructor don’t executes when an instance from the same class has been instantiated?
On GCC version 4.6 I got this
So it seems to be working
On a side note your base destructor should be virtual
this way when you only have a reference to the base you derived will still cleanly be removed.
On a side note, please don’t use defines like this unless you have too, also wrapping up mem in a smart point is also a good idea. Like auto_ptr in c++98 (ideally the boost ptrs) or unique_ptr in c++11.