Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I overload the operator& in C++

Tags:

c++

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?

like image 328
Andrey Bushman Avatar asked Sep 01 '25 05:09

Andrey Bushman


1 Answers

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;
}
like image 76
Joseph Mansfield Avatar answered Sep 02 '25 18:09

Joseph Mansfield