Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between "T a", "T a()" and "T a=T()" where T is a class?

Let T a C++ class.

Is there any difference in behaviour between the following three instructions?

T a;
T a();
T a = T();

Does the fact that T provides an explicit definition for a constructor that takes no parameter change anything with respect to the question?

Follow-up question: what about if T provides a definition for a constructor that takes at least one parameter? Will there then be a difference in behaviour between the following two instructions (in this example I assume that the constructor takes exactly one parameter)?

T a(my_parameter);
T a = T(my_parameter);
like image 322
Ramanewbie Avatar asked Dec 18 '25 02:12

Ramanewbie


1 Answers

T a; performs default initialization.

T a = T(); performs value initialization.

T a(); does not declare a variable named a. It actually declares a function named a, which takes no arguments and whose return type is T.

The difference between default initialization and value initialization is discussed here.

like image 91
Brian Bi Avatar answered Dec 20 '25 18:12

Brian Bi