2

In cpp, we can have primitive data-types initialized as

int a(32);

How does this constructor initialisation work? Does C++ treat it as an object?

HighCommander4
  • 50,428
  • 24
  • 122
  • 194
vagrawal13
  • 475
  • 2
  • 6
  • 15
  • What exact do you mean by "treats it as an object"? When it gets compiled it will move the literal constant `32` to the variables memory slot. Nothing more. So its just a syntax thing. – d_inevitable Jun 01 '12 at 02:40
  • 1
    No, in C++ the primitives are not treated as objects. As far as integers are concerned, this is just an alternative syntax for `a=32`. – Sergey Kalinichenko Jun 01 '12 at 02:41

2 Answers2

3

This is best described in:

C++03 8.5 Initializers
Para 12 & 13:

.......
The initialization that occurs in new expressions (5.3.4), static_cast expressions (5.2.9), functional notation type conversions (5.2.3), and base and member initializers (12.6.2) is called
direct-initialization and is equivalent to the form

T x(a);

If T is a scalar type, then a declaration of the form

T x = { a };

is equivalent to

T x = a;

In the question the type is int which is a scalar type.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

This is so-called direct-initialization. In C++, integers are not objects and the expression that you write here is not a constructor. It just initializes a to the value of 32.

Reinier Torenbeek
  • 16,669
  • 7
  • 46
  • 69
  • Got confused by the statement "The other way to initialize variables, known as **constructor initialization**, is done by enclosing the initial value between parentheses (()):" given here at http://www.cplusplus.com/doc/tutorial/variables/ – vagrawal13 Jun 01 '12 at 02:55
  • 1
    @vagrawal13: Yet another reason to avoid cplusplus.com. – Jerry Coffin Jun 01 '12 at 02:56
  • @vagrawal13: that statement is somewhat confusing indeed. For scalar types, the difference between the two different kinds of initialization is syntactic only. For objects of class type, the situation is more subtle. See [Is there a difference in C++ between copy initialization and assignment initialization?](http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati) for a good read. – Reinier Torenbeek Jun 01 '12 at 03:25