0

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;
}
user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 1
    Possible duplicate of [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user0042 Nov 09 '17 at 18:11
  • Unrelated: Use the combination of `#include` and `using namespace std;` with caution. Neither are recommended practice and together they can result in hard-to-comprehend bugs and errors. – user4581301 Nov 09 '17 at 18:11
  • For constructor `A(int a, int *f)` and copy operator better use deep copy. Also you need declare copy constructor and move constructor with deep copy, else you get leak memory. – svm Nov 09 '17 at 18:13
  • For a good write-up on @svm 's comment, read [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – user4581301 Nov 09 '17 at 18:14

1 Answers1

3

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.

vsoftco
  • 55,410
  • 12
  • 139
  • 252