-
Memory leaks!!!
i hav a doubt on memory leaks..
ok..we can assign a base pointer to a derived pointer(since derived has base+its own member functions)
lets say we hav
Base *baseptr = new Base;
Derived *derivedptr = new Derived;
baseptr=derivedptr;
delete baseptr;
Now if i call Delete baseptr..will it delete
whatever base pointer currently points to?
if this is true, there is no way i can access the actual(i.e before it was assigned to derivedptr) base pointer's contents..
Is this a memory leak? if so, what are the possible solutions?
-
This is a memory leak because you had two objects and you lost the pointer to one, analogous to:
Code:
int* a = new int;
int* b = new int;
a = b; //nothing pointing to the first int now
delete a;
If you want to cast a Base pointer to a derived pointer you'll need to know that this can only work if the Base pointer originally pointed to a derived object:
Code:
Base* b = new Derived;
Derived* d = dynamic_cast<Derived*>(b); //if we don't know that b points to Derived
if (d) {..} //cast successfull
delete b;
Edit:
Your confusion seems to be that you think a derived class would be constructed without the base part and you somehow manually need to combine them. This is not so, base class(es) are always constructed when you create a derived class, and you can cast towards base without any problem (first line of code).
-
One important rule to remember: Make sure that the destructor is virtual! If the destructor is not virtual, then you will only destroy the base-class, not the derived class. This isn't a problem for very basic classes, but the following would be:
Code:
class base {
public:
base(int ax = 0, int ay = 0) : x(ax), y(ay) {};
~base() { };
private:
int x, y;
};
class derived : public base {
public:
derived(int ax = 0, int ay = 0) : base(ax, ay), size(0), array(0) { };
~derived() { if (array) delete [] array;
void makeArray(int asize) {
size = asize;
array = new int[asize];
};
private:
int *array;
int size;
};
int main()
{
base *bp;
derived *dp = new derived();
dp->makeArray(100);
bp = dp;
deleete bp;
return 0;
}
Edit: Just to clarify - the above example is of course a bit contrived, why not just use dp all the way through. But in a real life scenario where the bp is for example a list of various objects that have their own class, and you delete the entire list as part of a destructor, it would of course delete the contents of this list (presumably), and that would cause the above type of failure, since bp->delete here calls the base destructor. If, on the other hand, we add virtual to the destructor, then it will call THAT OBJECTS destructor, and all will work fine, we don't get any memory leaks.
--
Mats