C ++: why is the constructor "A (A a) {}" illegal?

I met a quiz saying that the code below is poorly formed because "It is not allowed to have a constructor whose first and only argument is not the default value parameter for the class type."

I could not understand this. Why are things like A(A a) : val (a.val) {} illegal? why is such a line in the standard? Is this because it will lead to ambiguity with the copy constructor?

 #include <iostream> struct A { A() : val() {} A(int v) : val(v) {} A(A a) : val(a.val) {} int val; }; int main(int argc, char** argv) { A a1(5); A a2(a1); std::cout << a1.val + a2.val << std::endl; return 0; } 
+3
source share
3 answers

A(A a) : val(a.val) {} will lead to infinite recursion, since the constructor arguments are copied by value (calling the copy constructor and again the copy constructor and ...)

+7
source

The copy constructor is called when the object is passed by value. The copy constructor itself is a function. Therefore, if we pass an argument by value in the copy constructor, a copy constructor will be called to invoke the copy constructor, which becomes a chain of non-terminal calls . Therefore, the compiler does not allow passing parameters by value

It has already been discussed at this post. SO Why does the copy constructor accept its parameter by reference in C ++?

+3
source

Everything changes with const:

 #include <iostream> struct A { A () : _a(0) {} A (int a) : _a(a) {} A (const A& a) : _a(a._a) {} int _a; }; int main() { A a(5); A b(10); A c(a); std::cout << a._a + b._a + c._a << std::endl; // 20 return 0; } 
+1
source

Source: https://habr.com/ru/post/1210442/


All Articles