2

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);
Ramanewbie
  • 232
  • 1
  • 7

1 Answers1

8

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.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • 2
    There's also difference in that `T a = T();` is actually copy-initialisation. Prior to C++17, this would have implied that `T` must be copyable or movable. – eerorika Apr 23 '22 at 22:18
  • @Brian Bi regarding "T a(); does not declare a variable named a": what about "T a(my_parameter)" when the constructor takes one parameter? – Ramanewbie Apr 25 '22 at 12:20
  • 1
    @Ramanewbie That should work as intended because it cannot be interpreted as a function declaration. – Brian Bi Apr 25 '22 at 13:39