Question

I have been wondering a thing and couldn't find any relevant answers (maybe I'm just searching for the wrong things?) for this:

If a derived class exits scope (destructor is then called) will the base class members get destroyed too (even if the destructors are removed?).

The idea I get is that destructors are used to delete any dynamic memory or to close any hooks (files etc...). So if I have a managed member (string for example) will it still get destroyed?

Sorry if the question is stupid or has been answered before! Best Regards, Erik

Était-ce utile?

La solution

Yes, base class constructors are called when an instance of a derived class is destroyed. The one case you need to watch out for is if you delete a derived object via a pointer to the base:

class B
{
public:
   ~B();
}

class D : public B
{
public:
   ~D();
};

void f()
{
   B* p = new D();
   delete p; // will (probably) not call ~D()
}

To make cases like the above work, ~B() must be declared virtual.

class B
{
public:
   virtual ~B();
};

Autres conseils

Whenever an object gets out of scope its d-tor is being invoked - either the default compiler-provided one or user provided one.

If the object includes a base object (or objects) - all of their d-tors are called in a reversed order of the class inheritance definition order.

Then if you need to de-allocate dynamic memory in one of the base classes, simply make sure to provide a d-tor to deallocate the memory in that class

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top