Ron_s
Ron_s

Reputation: 1459

Delete is a member function ? destructor in private won't be invoked with delete?

Given the next code :

#include <iostream>
using namespace std;

class A
{
private:
    ~A () {}
};

int main()
{

    A *a = new A();
    delete a;
    return 0;

}

It doesn't compile .I thought that delete is a member function , isn't ? If so , shouldn't it have access to the dtor of A ?

Regrads ,Ron

Upvotes: 1

Views: 158

Answers (6)

Kerrek SB
Kerrek SB

Reputation: 476980

This has nothing to do with the delete operator. Rather, the problem is that the destructor is private, and when you call the delete expression delete a;, this is equivalent to a->~A(); ::operator delete(a); It is this first call to the destructor that fails, rather than the call of the delete operator.

Even if you overloaded member new/delete operators, that wouldn't change a thing, because it's the delete expression which first calls the destructor and then the (member) operator, so the destructor must be available as a public function.

Upvotes: 2

Patrick
Patrick

Reputation: 23619

You are confusing the call to delete, with the implementation of the delete method.

If you call delete, actually 2 things will happen:

  • the destructor is called
  • the memory is freed

By default, the memory will be freed by a default delete method. If you implement the delete method, your implementation should only free the memory, not call any destructor.

That's why you need access to both the delete method AND the destructor before you can call delete.

Upvotes: 1

Maxpm
Maxpm

Reputation: 25551

By that logic, this would be valid code:

class Foo
{
    Foo()
    {
    }
}

int main()
{
    // new is also a member function, right?
    Foo* Bar = new Foo;
}

Upvotes: 3

Clement Bellot
Clement Bellot

Reputation: 841

If you say to the compiler that a method is private, only the class can call it.

In you case, that means that only your class can delete itself.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

No, delete is not a member function; it's an operator. There is an operator delete() function which is invoked by the delete operator, but it's not a member unless you define it as such.

Upvotes: 3

sehe
sehe

Reputation: 392911

Solution to the riddle: no, delete is not a member function

Delete is an operator, that can be overloaded for a type, but not as a member function

Upvotes: 2

Related Questions