Copy-construct from reference

Consider this code

class Foo {
    Bar bar; //note: no reference

   Foo(Bar& b) : bar(b) { }

Will Bar get copy-constructed?


That depends on the signatures of Bar's public constructors, either explicitly or implicitly defined.

To start with, the C++ standard allows for implicit conversion of references as long as the only difference in the underlying type is that the destination type is at least as cv-qualified than the source type, using the partial ordering defined in this table (C++11, §3.9.3/4):

no cv-qualifier < const no cv-qualifier < volatile no cv-qualifier < const volatile const          < const volatile volatile    < const volatile

So, taking that into account as well as §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.

if Bar has a constructor with any of the following signatures:

Bar(Bar const&);
Bar(Bar volatile&);
Bar(Bar const volatile&);

then yes, b will be copy-constructed into Foo::bar.

EDIT: This was incorrect, I was thinking of operator= and the details of qualifying as a move-assignment operator.

Note that it's possible to have an eligible constructor that is not a copy constructor:


This will work (read: compile), but it is not technically a copy constructor.

Yes your member variable bar will be copy constructed, that's one of the benefits of using an initializer list as opposed to assigning the value in the body of the constructor.

If the Bar class does not have an accessible copy constructor and the compiler can't generate a default one, the code will fail to compile.

When you pass a reference to a copy constructor, you should generally make it a const reference.

Need Your Help

Link error using std::vector

c++ vector hyperlink std

I'm having a problem with a vector declaration. Here's the code: .h #ifndef ANIMATEDSPRITE_H_ #define ANIMATEDSPRITE_H_ #include "Sprite.h" #include &lt;vector&gt; //using namespace std; class

Howto Remove Garbage Data from String

python string parsing eeprom

I'm in a situation where I have to use Python to read and write to an EEPROM on an embedded device. The first page (256 bytes) is used for non-volatile data storage. My problem is that the variable...