Reputation: 1459
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
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
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:
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
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
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
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
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