Deleting a pointer to const (T const*)

Naveen picture Naveen · Apr 16, 2009 · Viewed 25.2k times · Source

I have a basic question regarding the const pointers. I am not allowed to call any non-const member functions using a const pointer. However, I am allowed to do this on a const pointer:

delete p;

This will call the destructor of the class which in essence is a non-const 'method'. Why is this allowed? Is it just to support this:

delete this;

Or is there some other reason?

Answer

anon picture anon · Apr 16, 2009

It's to support:

// dynamically create object that cannot be changed
const Foo * f = new Foo;

// use const member functions here

// delete it
delete f;

But note that the problem is not limited to dynamically created objects:

{
 const Foo f;
 // use it
} // destructor called here

If destructors could not be called on const objects we could not use const objects at all.