Tony
Tony

Reputation: 35

C++ return value from a class-member function

I can't understand why a.funct() can be the left operand of the assignment operator even if funct() is not returning a l-value reference.

class A
{
public: 
    A funct () {A x; return x;}
};

int main () 
{
    A a,b; a.funct()=b;
}

Upvotes: 1

Views: 2996

Answers (3)

Jarod42
Jarod42

Reputation: 217085

In the auto generated methods for the class, there is

A& operator = (const A&);

which make a.funct() = b legal.

To forbid affectation to rvalue, you may, since C++11, write and implement

A& operator = (const A&) &; // Note the last &

so assignation would only work for lvalue.

Upvotes: 5

Simon Kraemer
Simon Kraemer

Reputation: 5670

Your assumption is wrong. Your code is perfectly valid. Try this code:

#include <string>
#include <iostream>    

class A
{
    std::string m_name;
public:
    A(const std::string& name) :m_name(name) {}

    A funct() { A x("intern"); return x; }

    A& operator=(const A& a)
    {
        m_name += a.m_name;
        return *this;
    }

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

int main()
{
    A a("A"), b("B"); (a.funct() = b).print();//prints "internB"
}

Upvotes: 0

12345
12345

Reputation: 1

In the code, funct should return a variable that can be assigned to.

Note that the code in funct is very dangerous too if it were to be returned by reference; the local variable x will go out of scope once the function ends and the variable returned will cause undefined behaviour as its destructor will have been called.

Upvotes: 0

Related Questions