will this generate a memory leak?

Started by
3 comments, last by snk_kid 18 years, 10 months ago
code below: class A { ... }; class B : public A { ... }; ... A *pA = new B; delete pA; will this generate a memory leak?
Advertisement
No.

The "new" and "delete" operators don't care where you store the address that new returns. Your call to new creates an object of type B and returns the address. When you call delete, your giving it the address of that object, and it knows that the object at that address is of type B, and so it is successfully deleted.
You need to use a virtual deconstructor if you want to clean up the object properly unless neither class needs a deconstructor =)
Yeah, whenever you have inheritance, and you make use of polymorphism, you need a virtual destructor. What can happen otherwise is if you have an object which is really an instance of a derived class, but is being treated as the base type, if you then delete that object, it will call the base class destructor, and the derived class destructor will never be called. Eg, consider the following:

class BaseClass{public:	~BaseClass() {}};class ChildClass :public BaseClass{public:	~ChildClass() {}}void SomeFunc(BaseClass* object){	delete object;	}ChildClass* object = new ChildClass;SomeFunc(object);


When SomeFunc deletes the object, the BaseClass destrutor will be called instead of the ChildClass destructor. If your child class has memory allocated which needs to be released in the destructor, without the destructor being declared virtual, you will get a memory leak in this situation. Declaring the destructor virtual in the base class solves this problem.

Note that even with the destructor being declared virtual, when the ChildClass destructor completes, the BaseClass destructor will be called automatically; you don't have to call it explicitly.
Quote:Original post by Nemesis2k2
What can happen otherwise is if you have an object which is really an instance of a derived class, but is being treated as the base type, if you then delete that object, it will call the base class destructor, and the derived class destructor will never be called. Eg, consider the following...


I use to fall for this, apparently the standard states that its undefined behaviour in this situation add multiple-inheritance then what [wink], its implementation defined as to what may really happen, on one compiler it may do as you said on another it may actually do the correct behaviour still on another something completely different may happen.

As this is an implementation detail you shouldn't rely on it as it makes your code non-portable, so as a rule of thumb make the destructor (pure) virtual if you intend on invoking delete on pointers to base types, as this does have defined behaviour in the standard.

This topic is closed to new replies.

Advertisement