Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a destructor considered a const function?

Tags:

c++

destructor

Consider this

class Foo
{
public:
    Foo(){}
    ~Foo(){}
    void NonConstBar() {}
    void ConstBar() const {}
};

int main()
{
    const Foo* pFoo = new Foo();
    pFoo->ConstBar(); //No error
    pFoo->NonConstBar(); //Compile error about non const function being invoked
    delete pFoo; //No error 

    return 0;
}

In the main function I am calling both const and non const functions of Foo

Trying to call any non const function yields an error in Visual Studio like so

error C2662: 'Foo::NonConstBar' : cannot convert 'this' pointer from 'const Foo' to 'Foo &'

But delete pFoo doesn't issue any such error. The delete statement is bound to call the destructor of Foo class which doesn't have a const modifier. The destructor is also allowed to call other non const member functions. So is it a const function or not ? Or is delete on a const pointer a special exception?

like image 410
parapura rajkumar Avatar asked Sep 08 '25 13:09

parapura rajkumar


1 Answers

You can delete objects thorough constant pointers. In C++11, you can an also erase container elements through const-iterators. So yes, in a sense the destructor is always "constant".

Once the destructor is invoked, the object has ceased to exist. I suppose the question of whether a non-existing object is mutable or not is moot.

like image 117
Kerrek SB Avatar answered Sep 10 '25 03:09

Kerrek SB