Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class object creation in C++

Tags:

c++

object

class

I have a basic C++ question which I really should know the answer to.

Say we have some class A with constructor A(int a). What is the difference between:

A test_obj(4);

and

A test_obj = A(4);

?

I generally use the latter syntax, but after looking up something unrelated in my trusty C++ primer I realized that they generally use the former. The difference between these two is often discussed in the context of built-in types (e.g. int a(6) vs int a = 6), and my understanding is that in this case they are equivalent.

However, in the case of user-defined classes, are the two approaches to defining an object equivalent? Or is the latter option first default constructing test_obj, and then using the copy constructor of A to assign the return value of A(4) to test_obj? If it's this second possibility, I imagine there could be some performance differences between the two approaches for large classes.

I'm sure this question is answered somewhere on the internet, even here, but I couldn't search for it effectively without finding questions asking the difference between the first option and using new, which is unrelated.

like image 983
The Wind-Up Bird Avatar asked Dec 18 '25 13:12

The Wind-Up Bird


1 Answers

A test_obj = A(4); conceptually does indeed construct a temporary A object, then copy/move-construct test_obj from the temporary, and then destruct the temporary.

However this process is a candidate for copy elision which means the compiler is allowed to treat it as A test_obj(4); after verifying that the copy/move-constructor exists and is accessible.

From C++17 it will be mandatory for compilers to do this; prior to that it was optional but typically compilers did do it.

like image 179
M.M Avatar answered Dec 21 '25 03:12

M.M



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!