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 ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 parameterA aas 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 ofB 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-constructorsoption (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?