Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the first copy constructor is called in the code below ?

Why the B(B&) ctor is called, instead of B(const B&), in the construction of object b1 ?

#include <iostream>
using namespace std;

struct B
{
    int i;
    B() : i(2) { }
    B(B& x) : i(x.i) { cout << "Copy constructor B(B&), i = " << i << endl; }
    B(const B& x) : i(x.i) { cout << "Copy constructor B(const B&), i = " << i << endl; }
};

int main()
{
    B b;
    B b1(b);
}
like image 468
Belloc Avatar asked Dec 07 '22 16:12

Belloc


2 Answers

This is because overload resolution applies, and since the argument to the constructor of b1 is b, and b happens to be non-const lvalue, then the constructor taking non-const lvlalue is selected. And that's the first one. Interestingly, both are copy constructors, but your code would be equaly valid with just the latter one.

like image 129
bronekk Avatar answered Feb 23 '23 02:02

bronekk


Because b is not const. Therefore, it matches the first copy ctor perfectly, so that's what the compiler uses.

like image 31
Michael Kohne Avatar answered Feb 23 '23 02:02

Michael Kohne