Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor's signature without reference

If I have a Point class, the copy constructor should look like this:

Point(const Point &p);
Point(Point &p);

However, what if I want to create a constructor, which requires a Point? Why is it considered as copy constructor, instead of a constructor?

Point(const Point p)

Compiler error: "copy constructor for class "Point" may not have a parameter of type "Point"

like image 702
Ferenc Dajka Avatar asked Aug 01 '26 22:08

Ferenc Dajka


2 Answers

You can not have a copy constructor signature to accept the argument by value. The reason is simple - in order to pass parameter by value, you need to invoke copy constructor, which will require to pass parameter by value, and will invoke copy constructor... Welcome to endless recursion.

Compiler is saving you a lot of trouble by not allowing this construct.

like image 63
SergeyA Avatar answered Aug 04 '26 15:08

SergeyA


Point(const Point p)

Why is it considered as copy constructor, instead of a constructor?

It's not.

As the standard says in §12.8/2:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (...).

In fact, your declaration is ill-formed. §12.8/6 says:

A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv-qualified) X and either there are no other parameters or else all other parameters have default arguments.

You do have exactly that: a constructor for a class Point whose first parameter is of type const Point and there are no other arguments.

This is of course the formal explanation. As others have explained, the practical implication of such a constructor would be infinite recursion.

Perhaps you are concerned about the error message you got. However, there are absolutely no rules regarding the contents of a diagnostic message produced by a compiler. It's a quality-of-implementation issue; if your compiler thinks that copy constructor for class "Point" may not have a parameter of type "Point" is a good way to convey the problem to its users, then so be it.

like image 34
Christian Hackl Avatar answered Aug 04 '26 14:08

Christian Hackl



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!