Click here to Skip to main content
15,741,818 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everybody,
Here is my problem:
I have an abstract class called CPersonel and I have derived CExecutive from this class. Next, I have drived CTechExecutive from CExecutive.
Now in my code, I make a reference to CPersonel and I use it to make a new instance of its derived class like this:

CPersonel* personel;<br />
personel = new CTechExecutive;

What's wrong with this implementation, cause it leads in to memory leakage. Is there any limit in moving through layers of hierarchy while making use of polymorphism?
I'll appreciate if you guys help me on this!

Use virtual destructors for base classes and any class with virtual functions. If you are still having problems, you can temporarily add a static counter of the various objects, incrementing with every constructor call and decrementing after a destructor. That way you can see which destructor is not being called.
Share this answer
I assume you already know this, but I have to make sure:
The two lines of code you posted are a memory allocation. The memory will be used until you release it with a call to delete:

delete personel;

This is C++ after all - as I said I assume you already know this.

The second catch is the destructor declaration - if you want to use a base class pointer to reference objects it's important to keep the destructors virtual:

virtual ~CPersonel()

otherwise the call to delete the object made via a base class pointer will not cause the derived class destructor to be called. Sometimes this is hard to spot, but if you make any allocations in the derived class constructor - there's your leek.
Share this answer
Maryam Kasravi 4-Jan-11 3:13am    
Yes, indeed I have not mentioned those parts as I assumed it as a must. But your second catch worked, Thanks a lot, for your kind help, I never knew this before.
Emilio Garavaglia 5-Jan-11 2:26am    
Maryam, if you "never knew about this", than don't limit to virtual destructors, but study a while what virtual fiction are and work (virtual destructors -after all- are just a particular case). You may need them soon!
The information provided is insufficient to help you. But the guess is you aren't removing all of the memory allocations that were made in the constructor in the destructor. You better take a closer look at these two functions of all the classes in the hierarchy. If things are proper there, it might be that in the life span of these class objects, some operations might have allocated memory which are not deallocated.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900