Destructing objects using base class pointer

Nov 28, 2011 at 12:41am
Hello

I want to know if it it safe to destroy an object using a pointer of its base class type, for example, would this free all memory?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class a1 {
   public:
     int i;
}

class a2 : public a1 {
   public:
     int i2;
}

int main() {
   a1* aa2 = new a2; 
   delete aa2;
}


in this case will the allocated memory be fully freed or will the delete only deallocate the memory that the base class occupies?

And also, as you probably can tell already, i don't really know how delete knows how much memory to dealocate, so if someone could explain it to me, or at least point me to an article that would explain it i would be very grateful.

Thanks for the attention.
Nov 28, 2011 at 12:50am
No this is not safe. The base class must have a virtual destructor.

1
2
3
4
5
6
7
8
9
10
class a1 {
   public:
     virtual ~a1(){}  
     int i;
};

class a2 : public a1 {
   public:
     int i2;
};


Now it should work safely.
Last edited on Nov 28, 2011 at 12:50am
Nov 28, 2011 at 12:52am
This site has a great article on dynamic memory.

http://www.cplusplus.com/doc/tutorial/dynamic/
Nov 28, 2011 at 1:29am
Ok, then does that mean that delete works based on the type of the given pointer?
Nov 28, 2011 at 1:31am
yes the type is important
Nov 28, 2011 at 2:03am
Ok then, thanks for your time
Topic archived. No new replies allowed.