First of all - when you're making classes derive from one another, you should make sure the destructors are virtual
. If you don't, you may have memory leaks when the deriving classes have additional members:
virtual ~Base ( )
{
cout << "Inside Base destructor" << endl;
}
Secondly - when you allocate memory using new
, the destructor won't be called on the created object, untill you manually delete it with delete
:
int main( )
{
Derived y;
Derived2 *ptr = new Derived2();
Derived2::bogus(ptr);
delete ptr;
return 0;
}
If you're unsure on when to delete the object, use std::shared_ptr
or delete it inside the destructor of the class taking it as the parameter. Note that shared_ptr
is available only for C++11, if you're using an older version (like still many people are), try using the boost library.