c++ : Whats difference in "catching reference in value" vs "catching value in value" during function return?

61 views Asked by At

What exactly happens at 1 & 2 internally , when we have assigned by return reference?

Class A
{
    A& operator= (const A &ax)
    {
        return *this;
    }
}
int main()
{
    A a;
    A b;
    b = a; // -------------- 1
    A c = a;  // ----------- 2
}

// ---------------------------------------------------------------

What difference will happen in below (assigned returned value)? :

Class A
{
    A operator= (const A &ax)
    {
        return *this;
    }
}
int main()
{
    A a;
    A b;
    b = a; // -------------- 3
    A c = a;  // ----------- 4
}
1

There are 1 answers

10
Swift - Friday Pie On

There is also principal mistake, because operator= made private and code is ill-formed, but this would be corrected by adding public: access modifiers.

operator= is invoked from object stored to b variable, so this variant of assignment should not perform assignment at all.

#include <iostream>

class A
{
public:
    float a1;

    A& operator= (const A &ax)
    {
        return *this;
    }
};

int main()
{
    A a; 
    a.a1 = 3;

    A b; 
    b.a1 = 5;

    b = a; // -------------- 1

    std::cout << b.a1; // outputs 5

    A c = a;
    std::cout << c.a1; // outputs 3

}

The line

A c = a;

is called initialization and doesn't use operator=, instead it uses (generated by compiler) copy constructor, which does a shallow copy of object.

Your mistake is that member operator= meant to assign its argument's value to this. operator= return result of assignment, which can be used for chaining: a=b=c;

A& A::operator= (const A &right)

is equivalent of

A& operator= (A &left, const A &right)