vendredi 29 mai 2020

Why does the compiler complains when `none const copy constructor` is used?

As the subject, the code below is right.

#include<iostream>

class ABC     
{  public:  
    ABC() 
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(ABC& a) 
    {
        std::cout << "copy construction" << std::endl;
    } 

};                         

int main()   
{  
   ABC c1 = ABC(); 
}

It could not compile successfully:

<source>: In function 'int main()': 
<source>:25:13: error: cannot bind non-const lvalue reference of type 'ABC&' to an rvalue of type 'ABC'
   25 |    ABC c1 = ABC();
      |             ^~~~~
<source>:10:14: note:   initializing argument 1 of 'ABC::ABC(ABC&)'
   10 |     ABC(ABC& a)
      |         ~~~~~^

However, it could compile if replace the ABC(ABC& a) by ABC(const ABC&).I know it has some relation with the keyword const.But i could not figure out why.

You could check it on https://godbolt.org/z/jNL5Bd. I am a novice in C++.I would be grateful to have some help with this question.

Aucun commentaire:

Enregistrer un commentaire