class A {};
class B { public: B (A a) {} };
A a;
B b=a;
Technically speaking, is a copy constructor being applied here on the creation of b
?
class A {};
class B { public: B (A a) {} };
A a;
B b=a;
Technically speaking, is a copy constructor being applied here on the creation of b
?
Yes, in theory. This is copy-initialiation. First a temporary B
instance is constructed from the initializer (a
), then b
is initialized from this temporary via the copy constructor.
Compilers are allowed to, and frequently do, elide the temporary and the copy construction, though, and construct b
directly from a
using the B(A)
constructor.
Technically speaking, is a copy constructor being applied here on the creation of b ?
Yes...but probably not how you think. A
's copy constructor is being invoked on the creation of b, in order to do the pass-by-value of the parameter A a
as a parameter to the B constructor.
However, it is not running B's copy constructor in the creation of b.
EDIT: One learns something new every day. Apparently even more-technically-speaking, as @CharlesBailey pointed out...if you use the B b = a;
syntax ("copy initialization") instead of B b (a);
syntax ("direct initialization"), a temporary value of type B might need to be created. At this point B's copy constructor would wind up being called.
It's a little hard to study the phenomenon, but Charles points out that gcc has a -fno-elide-constructors
option (also: Wikipedia on Copy Elision) @JesseGood's link has an exhaustive explanation and some demonstration code:
Is there a difference in C++ between copy initialization and direct initialization?
No, a copy constructor takes a reference to an object of the same kind.
C++03 12.1 Constructors
- A copy constructor for a class X is a constructor with a first parameter of type
X&
orconst X&
.
EDIT: OK, to be fair (and after reading the other answers), a copy constructor is being called, but it's A
's copy constructor. I thought you meant B
's.
EDIT2: To be fairer, it's not necessary for it to be called at all:
A a;
B b = a; //called
B c = A(); //probably not called due to copy elision
No. It's not a Copy Constructor.
If you creates an object by initializing it with an object of the same class, that is copy constructor.
A a;
A b=a;
The above code is copy Constructor.