Search code examples
c++operator-overloadingassignment-operator

Assigning object after operation via operator


I want to add contents of two classes and save them in another class. I have created constructor, parameterized constructor, destructor and overloaded = parameter. It is working fine for Demo b = a; but when I try to save the object given by a.addition(b), there's error no viable overloaded '='. My concept is why the object is not getting copied to newly created object?

Class Demo

class Demo
{
    int* ptr;
public:
    Demo(int data = 0) {
        this->ptr = new int(data);
    }
    ~Demo(void) {
        delete this->ptr;
    }
    // Copy controctor
    Demo(Demo &x) {
        ptr = new int;
        *ptr = *(x.ptr);
    }
    void setData(int data) {
        *(this->ptr) = data;
    }
    int getData() {
        return *(this->ptr);
    }

    Demo operator = (Demo& obj) {
        Demo result;
        obj.setData(this->getData());
        return result;
    }

    Demo addition(Demo& d) {
        Demo result;
        cout << "result: " << &result << endl;
        int a = this->getData() + d.getData();

        result.setData(a);

        return result;
    }
};

Main

int main(void)
{
    Demo a(10);
    Demo b = a;
    Demo c;
    c = a.addition(b); // error here
    return 0;
}

Solution

  • The operator= takes a referecne to non-const (i.e. Demo&) as its parameter, which can't bind to the temporary object returned by addition.

    To solve the issue you should change the parameter type to reference to const (i.e. const Demo&), which could bind to temporary and is conventional.

    BTW: The target and source of the assignment seem to be opposite. I suppose it should be implemented as

    Demo& operator= (const Demo& obj) {
        setData(obj.getData());
        return *this;
    }
    

    And declare getData as a const member function.