0

Possible Duplicate:
What do the following phrases mean in C++: zero-, default- and value-initialization?

There are multiple places where people have said that an explicit call to the class constructor results in value initialization [when no used-defined constructors exist] and that this is not done by the default constructor [which is a do-nothing constructor] but is something completely different.

What happens actually if no constructor is called OR What is value initialization in this case ?

Community
  • 1
  • 1
asheeshr
  • 4,088
  • 6
  • 31
  • 50
  • There is always the standard that documents this behaviour, but i guess that wasn't what you meant, or was it? – PlasmaHH Aug 21 '12 at 15:26
  • *is there documentation that supports/mentions/explains this behaviour?* Yes, it is called *The Standard* – David Rodríguez - dribeas Aug 21 '12 at 15:27
  • 1
    Check this: [What does 'value initializing' something mean?](http://stackoverflow.com/questions/8860780/what-does-value-initializing-something-mean) – Alok Save Aug 21 '12 at 15:27
  • That was fast o.O Thanks for pointing that out @Als. Didnt find it while searching. – asheeshr Aug 21 '12 at 15:39
  • Am i missing something ? As per your answer, eg. class A { int i; }; A x = A(); -> Value initialization so i=0. Fine. A x -> Default initialization, this is POD class type, hence it should also be zero initialized ?? – asheeshr Aug 21 '12 at 15:53
  • @Als, could you please explain ? – asheeshr Aug 22 '12 at 13:55

2 Answers2

0

Firstly, what happens actually if no constructor is called

A constructor for a class-type is always called when an object is constructed, be it user-defined or compiler-generated. The object is initialized, but the members can remain un-initialized. This makes the second part of the question obsolete.

Second, is there documentation that supports/mentions/explains this behaviour ?

The all-mighty standard.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

This is only true for aggregates: Consider this:

struct Holder
{
   Aggregate a;
   NonAggr   n;

   Holder(int, char) : a(), n() { }
   Holder(char, int) { }
};

Holder h1(1, 'a');
Holder h2('b', 2);

Suppose Aggregate is an aggregate type. Now h1.a is value-initialized, which value-initializes each member, while h2.a is default-initialized, which default-initializes each member. The same holds for the n member, but if NonAggr is a non-aggregate class type, its default constructor will always be called.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084