Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ variable declaration and initialization rules

Consider the following ways of declaring and initializing a variable of type C:

C c1;

C c2;
c2 = C();

C c3(C());

C c4 = C();

Are all of these completely equivalent to each other, or can some of these differ depending on the exact definition of C? (assuming it has public default and copy constructors).

like image 419
Roman Starkov Avatar asked Mar 24 '26 10:03

Roman Starkov


1 Answers

These mean:

C c1;   // default constructor

C c2;   // default constructor
c2 = C(); // default constructor followed by assignment

C c3(C());   // default constructor possibly followed by copy constructor

C c4 = C();  // default constructor possibly followed by copy constructor

Note the compiler can elide copy constructor calls. Are they equivalent? - well, it depends on what the copy constructor and assignment operator do.


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!