Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: why constructor "A(A a) {}" is illegal? [duplicate]

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

I couldn't understand that. Why things like A(A a) : val (a.val) {} is ruled as illegal? why such a line in the standard? Is it because this will lead to ambiguity with 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;
}
like image 220
athos Avatar asked Dec 31 '25 21:12

athos


1 Answers

A(A a) : val(a.val) {} will cause an infinite recursion because constructor arguments are being copied by value (invoking copy constructor and again the copy constructor and ...)

like image 193
Mohit Jain Avatar answered Jan 03 '26 12:01

Mohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!