Reputation: 151
int main()
{
A* x = new B(10, 20);
x->opt1();
delete x;
return 0;
}
int main()
{
B x(10, 20);
return 0;
}
So, the first has a memory leak, I understand that because x is an A object that points to a B object. If A was not a pointer would it still have a memory leak?
And why does the second function not have a memory leak? We don't need to delete x?
class A
{
private:
int* a;
public:
A(int size) {
a = new int[size];
}
~A() {
if (a) {
delete [] a;
}
};
virtual void opt1() {
cout << "A::opt1()" << endl;
}
};
class B : public A
{
private:
float* b;
public:
B(int size1, int size2) : A(size1) {
b = new float[size2];
}
~B() {
if(b){
delete [] b;
}
}
virtual void opt1() {
cout << "B::opt1()" << endl;
}
};
Upvotes: 0
Views: 301
Reputation: 173044
the first has a memory leak, I understand that because x is an A object that points to a B object.
No, there's no memory leak if A
and B
have well-defined inheritance relationship. Such as:
class A {
public:
virtual ~A() {}
};
class B : public A {
};
why does the second function not have a memory leak?
Because x
is allocated on stack, which don't need and can't call delete
on it. x
will be destroyed automatically.
We don't need to delete x?
Only object created by new
need to delete
.
EDIT
For you code of A
and B
, the first case will lead to memory leak, because A
(the base class) 's destructor is not virtual. For
A* x = new B(10, 20);
delete x;
only the destructor of A
will be called, the destructor of B
won't be called, that means float* b
inside B
won't be deallocated.
It's a bad idea if you want to use them in this way, i.e. deleting an instance of a derived class through a pointer to base class.
See When to use virtual destructors?
Upvotes: 3
Reputation: 57804
In the second, new
was not explicitly called, though the item's constructor was. But the variable goes out of scope automatically as so the destructor being automatically called prevents any sort of leak, provided the destructor is correctly written to counteract any internal allocations within the object.
I would think the first example would not be a memory leak, but maybe there is some fine point of a based class which causes a problem.
Upvotes: 2