Destructing objects using base class pointer

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.
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
This site has a great article on dynamic memory.

http://www.cplusplus.com/doc/tutorial/dynamic/
Ok, then does that mean that delete works based on the type of the given pointer?
yes the type is important
Ok then, thanks for your time
Topic archived. No new replies allowed.