Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an old C++ style constructor?

Tags:

c++

c++11

Here a piece of C++ code.

In this example, many code blocks look like constructor calls. Unfortunately, block code #3 is not (You can check it using https://godbolt.org/z/q3rsxn and https://cppinsights.io).

I think, it is an old C++ notation and it could explain the introduction of the new C++11 construction notation using {} (cf #4).

Do you have an explanation for T(i) meaning, so close to a constructor notation, but definitely so different?

struct T {
   T() { }
   T(int i) { }
};

int main() {
  int i = 42;
  {  // #1
     T t(i);     // new T named t using int ctor
  }
  {  // #2
     T t = T(i); // new T named t using int ctor
  }
  {  // #3
     T(i);       // new T named i using default ctor
  }
  {  // #4
     T{i};       // new T using int ctor (unnamed result)
  }
  {  // #5
     T(2);       // new T using int ctor (unnamed result)
  }
}

NB: thus, T(i) (#3) is equivalent to T i = T();

like image 209
Pascal H. Avatar asked Nov 25 '19 15:11

Pascal H.


People also ask

Does C struct have constructor?

3. Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.

Should you use the this pointer in the constructor?

Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the { body } and even in the initialization list) if you are careful.

What happens if you do not provide any constructor to a class in c++?

If no constructors are declared in a class, the compiler provides an implicit inline default constructor. If you rely on an implicit default constructor, be sure to initialize members in the class definition, as shown in the previous example.

Does every class have a default constructor c++?

No default constructor is created for a class that has any constant or reference type members. A constructor of a class A is trivial if all the following are true: It is implicitly declared. or explicitly defaulted.


1 Answers

The statement:

T(i);

is equivalent to:

T i;

In other words, it declares a variable named i with type T. This is because parentheses are allowed in declarations in some places (in order to change the binding of declarators) and since this statement can be parsed as a declaration, it is a declaration (even though it might make more sense as an expression).

like image 73
Brian Bi Avatar answered Sep 17 '22 19:09

Brian Bi