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?
The object would be destroyed automatically and the destructor would be called as the object went out of scope when foo returns.
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(); };
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.
Yes, delete[] guarantees destructors are called on every object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With