Search code examples
c++operator-overloadingassignment-operator

how to overload assignment operator to satisfy ob1=ob2=ob3 (ob1,ob2,ob3 are objects of same class)


how to overload assignment operator to satisfy ob1=ob2=ob3 (ob1,ob2,ob3 are objects of same class) where we have no concern for (ob2 = ob3) which is similar to (ob2.operator=(ob3)) but we need a parameter of type class when we are assigning this result to ob1 which is similar to (ob1.operator=(ob2.operator=(ob3)) below is the code that gives me error

#include<bits/stdc++.h>
using namespace std;
class A
{
public:
    int x;
    int *ptr;
    A()
    {
    }
    A(int a, int *f)
    {
        x = a;
        ptr = f;
    }
    void operator=(A&);
};
void A::operator=(A &ob)
{
    this->x = ob.x;
    *(this->ptr) = *(ob.ptr);
}
int main()
{
    int *y = new int(3);
    A ob1, ob2, ob3(5, y);
    ob1 = ob2 = ob3;
    cout << ob1.x << " " << *(ob1.ptr) << endl;
    cout << ob2.x << " " << *(ob2.ptr) << endl;
    cout << ob3.x << " " << *(ob3.ptr) << endl;
    return 0;
}

Solution

  • Your asignement operator should return a reference to *this, and be defined as

    A& operator=(const A&);
    

    or, better, pass by value and use the copy-and-swap idiom

    A& operator=(A);
    

    For an excellent intro to operator overloading, see this.