Luv
Luv

Reputation: 5471

Behaviour of copy constructor accepting const reference

In the following Code, in this line

A(A& b)

When using this compiler gives error as

c110.cpp:41: error: no matching function for call to ‘A::A(A)’

c110.cpp:8: note: candidates are: A::A(A&)

But as soon as i convert it into

A(const A& b)

Many many thanx in Advance

No error comes. Why is it so?

Code
class A
{
    public: 
    static int cnt;
    A(A& b)
    {
       cnt++;
       cout<<"cnt="<<cnt<<endl;
    }
    A()
    {
       cnt++;
       cout<<"cnt="<<cnt<<endl;
    }
    ~A()
    {
       cnt--;
       cout<<"cnt="<<cnt<<endl;
    }
};



  int A :: cnt=0;


  A fun(A b)
  {
  return b;
  }


 int main()
 {
     A a;
     A b=fun(a);
     return 0;
 }

Upvotes: 1

Views: 183

Answers (2)

Luv
Luv

Reputation: 5471

I think its always safe to use A(const A&) type of syntax for copy construction rather than A(A&), because RVO may take place or not, its compiler dependent.

As in the above question RVO is not taking place and the temporary is been created, hence A(const A&) is safe to use.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258698

Non-const references cannot bind to temporaries. If you pass a temporary as parameter, A& is illegal but const A& isn't.

The line

A b=fun(a);

does copy-initialization on the object returned by fun(a), which is a temporary.

Also, the copy constructor shouldn't take a non-const reference because, logically, you don't need to modify the object you're copying from.

Upvotes: 10

Related Questions