1

Code:

class A 
{
public:
    A()
    {
        cout<<"Defualt Constructor"<<endl;
    }

    A(A &t) 
    { 
        cout<<"Copy Constructor"<<endl;
    }
};

A func()
{
    cout<<"In func"<<endl;
}

int main()
{
    A a1;
    A a2;
    a2 = func();
    return 0;
}

The program works fine. Also, If I call function like this:

A a2 = func();

and add const qualifier in copy constructor argument like:

A(const A &t) 
{ 
    cout<<"Copy Constructor"<<endl;
}

Also, working fine.

But, If remove const from copy constructor argument like:

A(A &t) 
{ 
   cout<<"Copy Constructor"<<endl;
}

and call function func()

A a2 = func();

Compiler giving an error:

error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'
      A a2 = func();
                 ^
prog.cpp:13:9: note:   initializing argument 1 of 'A::A(A&)'
         A(A &t) 
         ^

Why does compiler give an error in last case?

msc
  • 33,420
  • 29
  • 119
  • 214

1 Answers1

7

A a2 = func(); is copy initialization, a2 will be initialized from the object returned by func() via copy constructor. func() returns by value, so what it returns is a temporary, which can't be bound to lvalue-reference to non-const (i.e. A &), that's why you get the error.

Temporary could be bound to lvalue-reference to const (or rvalue-reference), so changing the parameter type to const A &t (or adding move constructor) would make it work fine.

BTW: a2 = func(); has nothing to do with copy constructor, but copy assignment operator. You didn't declare it for A, and the implicitly declared copy assignment operator takes const A& as parameter, then it's fine.

BTW2: func() returns nothing. Note that flowing off the end of a non-void function without returning leads to UB.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405