Reputation: 12516
How can I overload the operator& in C++? I've tried this:
#ifndef OBJECT_H
#define OBJECT_H
#include<cstdlib>
#include<iostream>
namespace TestNS{
class Object{
private:
int ptrCount;
public:
Object(): ptrCount(1){
std::cout << "Object created." << std::endl;
}
void *operator new(size_t size);
void operator delete(void *p);
Object *operator& (Object obj);
};
void *Object::operator new(size_t size){
std::cout << "Pointer created through the 'new' operator." << std::endl;
return malloc(size);
}
void Object::operator delete(void *p){
Object * x = (Object *) p;
if (!x->ptrCount){
free(x);
std::cout << "Object erased." << std::endl;
}
else{
std::cout << "Object NOT erased. The " << x->ptrCount << "references are exist."
<< std::endl;
}
}
Object *Object::operator& (Object obj){
++(obj.ptrCount);
std::cout << "Counter is increased." << std::endl;
return &obj;
}
}
#endif
Tne main function:
#include<iostream>
#include"Object.h"
namespace AB = TestNS;
int main(int argc, char **argv){
AB::Object obj1;
AB::Object *ptrObj3 = &obj1; // the operator& wasn't called.
AB::Object *ptrObj4 = &obj1; // the operator& wasn't called.
AB::Object *obj2ptr = new AB::Object();
}
The output result:
Object created.
Pointer created through the 'new' operator.
Object created.
My operator& wasn't called. Why?
Upvotes: 4
Views: 3619
Reputation: 20759
The sftrabbit answer is correct about syntax, but beware that what you are doing with new
and delete
is not congruent.
the new and delete operator work on raw memory, not on constructed object.
When you do A* p = new A
...
operator new
is called and ...A
constructor is than called over the returned memory address and ...A*
and given to p
.Similarly, when you do delete p
...
A
destructor is called and...operator delete
to be given back to the system.In both the situation the state of A
object instance (the value of its members) is undefined:
operator new
whatever thing you do, will be overwritten by the subsequent constructor call. In case the constructor does not initialize something, the standard says it's value is undefined (and not granted to be the same you can set in new
).operator delete
whatever thing you do is done on an already dead object (and what you found inside it is not granted to be the "last live state".In any case the object dies when you call delete. You cannot "save it from dead" during operator delete
(that's called after destruction). It's purpose is to place the tombstone, not to reanimate the cadaver.
Upvotes: 2
Reputation: 110738
You are currently overloading the binary &
operator (i.e. bitwise AND). To overload the unary &
operator, your function should take no arguments. The object it applies to is that pointed to by this
.
Object *Object::operator& (){
++(this->ptrCount);
std::cout << "Counter is increased." << std::endl;
return this;
}
Upvotes: 15