Why should we use the link in the copy constructor argument instead of the pointer?

Why should we use the link in the copy constructor argument instead of the pointer? These questions were asked in an interview. I answered the following questions:

  • Links cannot be NULL.
  • If we use a pointer, this will not be a copy constructor.
  • The standard defines this (section 12.8.2).

But the interviewer was not satisfied. He said that it is "related to inheritance and virtual functions." I need help or some important points with which I can think of an answer in this direction.

+5
source share
2 answers

Your interviewer was wrong, and you are right.

The most important aspect of your answer is 2. and 3 (which are essentially the same, but formulated differently): because the standard says this ( see 12.8.2 ):

A constructor without a template 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 all other parameters have default arguments (...).

We use links instead of pointers because the standard says so . This is not a copy constructor.

When it comes to inheritance and virtual functions, links can do whatever the pointer can contain.

The only reason you could provide, as Gautam Jha points out in the comments , is that the link allows you to make a copy from temporary.

+2
source

You consider it reasonable, and I cannot understand what your interviewer wanted to hear from you.

But as far as I know, the ability to have consistent syntax for copy constructors and assignment operators was an important reason Stroustrup introduced links. For example, suppose we have no C ++ references, and we want to make some copy construct by passing the argument with a pointer:

 class MyClass { // Copy ctor and assignment operator are declared // like this in our referenceless "C with classes" language: MyClass(const MyClass* const); MyClass* operator=(const MyClass* const); }; MyClass a, b, c; //Let copy-construct: MyClass d = &a; // Dereferencing looks ugly. //Let assign: a = &b; // Dereferencing again. // Even worse example: a = b = c = &d; // Only the last variable should be dereferenced. a = b = &c; // Awfully inhomogeneous code. /* The above line is equivalent to a = (b = &c), where (b = &c) returns a pointer, so we don't need to dereference the value passed to assignment operator of a. */ 

And this is clearly not how the built-in types work:

 int a, b, c; int d = a; a = b = c = d; 

Links have been introduced to resolve these heterogeneities.

UPD

For authoritative proof of this point, please refer to Β§ 3.7 "Stroustrup Design and C ++ Evolution". Unfortunately, I do not have the English text of the book, but the first sentence in this chapter (back-translated into English):

Links were introduced primarily to support operator overloading.

And in the next few pages, Stroustrup describes the topic in detail.

+2
source

All Articles