jeudi 23 août 2018

Confusion about Copy Constructor in C++

Code:

#include<iostream>
using namespace std;

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?

Aucun commentaire:

Enregistrer un commentaire