Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does copy constructor that returns value, discards the temp?

having this code:

#include <iostream>

class Base {
public:
    Base() = default;

    explicit Base(int val) : _var(val) {}

    Base operator=(const Base &rhs) {
        _var = rhs._var;
        return *this;
    }

    void print() const {
        std::cout << _var << std::endl;
    }

private:
    int _var;
};

int main() {
    Base b[] = {Base(10), Base(), Base(), Base()};
    (b[1] = b[2]) = b[0];
    for (Base base: b) {
        base.print();
    }
}

the output is:

10
0
0
0

but I would expect

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

10
10
0
0

As the second element in array b[1] should get assign from b[0], but the assignment operator returns value, not reference and thus copy-constructing happen. But still, why is not b[1] copy-constructed to have _var=10?

If the operator= returned Base &, the output would be my expectation

>Solution :

To get the desired result of your assignment operator (which, by the way, is different from copy constructor), you need to return a reference:

Base& operator=(const Base &rhs)

This is the canonical form.

Without the reference, the result of (b[1] = b[2]) is stored in a temporary. (b[1] = b[2]) = b[0]; assigns to that temporary, which is discarded and has no effect on b[1].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading