#include <iostream>
using namespace std;
class base
{
int a;
public:
base() {a =0;}
};
class derv :public base
{
int b;
public:
derv() {b =1;}
};
int main()
{
base *pb = new derv();
delete pb;
}
I don't have a virtual destructor in derv class, does it delete only base part of derv object??
There is no memory leak in your code. There would have been a memory leak if you needed to free some memory in the derived class destructor.
It might.
Because
base
does not have a virtual destructor, your code exhibits undefined behavior. Anything might happen. It might appear to work as you expect. It might leak memory. It might cause your program to crash. It might format your hard drive.A citation was requested. C++11 §5.3.5/3 states that, for a scalar
delete
expression (i.e., not adelete[]
expression):The static type (
base
) is different from the dynamic type (derv
) and the static type does not have a virtual destructor, so the behavior is undefined.In your source code there is no memory leak, since you don't have any member variable that is created dynamically.
Consider the modified example below Case 1:
In this case the output will be,
In this case there is a memory leak, because 'b' is created dynamically using 'new' which should be deleted using 'delete' keyword. Since derv destructor is not being called it's not deleted so there is memory leak.
Consider the below case 2:
In the case 2 output will be,
In this case there is no memory leak.because derv destructor is called and b is getting deleted.
Destructor can be defined as Virtual in base class to make sure the derived class destructor to be called when we delete base class pointer which is pointing to derived class object.
We can say 'Destructor must be virtual when derived class has dynamically created members'.