Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destruction of class members when destructor is not called

Tags:

c++

In the following code, when ptr is deleted, the destructor for Base is called, but not the destructor for Derived (due to destructor of Base not being virtual).

class Base
{
  int b;
};

class Derived : public Base
{
  int d;
};

int main(void)
{
    Base * ptr = new Derived();
    delete ptr;
    return 0;
}

Valgrind reports that the program contains no memory leaks, which i guess is true in the sense that all newed data is deleted in this particular case. My question is - given that the (default) destructor of Derived is not called, when and how is the memory for d deallocated or reclaimed?

like image 278
Vandhunden Avatar asked Feb 22 '13 11:02

Vandhunden


People also ask

What happens when destructor is not called?

The object would be destroyed automatically and the destructor would be called as the object went out of scope when foo returns.

What happens when destructor is called?

A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For example: class X { public: // Constructor for class X X(); // Destructor for class X ~X(); };

When an object is destroyed destructor is automatically called?

A destructor is a member of a function which is automatically called when the class is destroyed. It has the same name as the class name but is preceded by a tilde (~). Normally a destructor is used to clean-up when the class is destroyed. C++ Program 12.1 has a class which is named class_ex.

Does delete [] call destructor?

Yes, delete[] guarantees destructors are called on every object.


1 Answers

It is Undefined behavior to call delete on a base class pointer pointing to a derived class object if the destructor in base class is not virtual.

Undefined behavior means that anything can happen. Whether memory leaks or not is irrelevant the fact is that your program can show any behavior and you cannot rely on any behavior that is shown.

For your code to be valid the destructor in Base class must be virtual.


C++11 Standard 5.3.5 Delete:
Para 3:

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

like image 129
Alok Save Avatar answered Oct 03 '22 07:10

Alok Save