codymanix
codymanix

Reputation: 29468

Variable initialising and constructors

I am currently taking a c++ course and trying to get a deep understanding of the whole thing. I came up with some theories, it would be great if somebody could confirm them:

Every variable (local,global,staic,member and non-member) is guaranteed to have its ctor called before first use

The ctors of primitives like int are essentially no-ops, so we have explicitly assign a value, there is no default zero value.

the following classes are semantically the same (and should generate identical code)

class A 
{ 
  int n; 
};

and

class A 
{
  int n;
 public:
  A() : n() {}
};

and

class A 
{
  int n;
 public:
  A() { n = int(); }
};

The variable n is in every case still uninitialized.

EDIT:

It seem that I absolutetly underestimated the complexity of this subject, most of my assumptions were wrong. Now Iam still trying to find out the basic rules of object initialisation.

Upvotes: 2

Views: 3206

Answers (4)

Nitesh
Nitesh

Reputation:

class A 
{ 
   int n; 
};

Only memory is allocated, no initialization done for n.


class A 
{
  int n;
 public:
  A() : n() {}
};

Here n is initialized with 0.


class A 
{
  int n;
 public:
  A() { n = int(); }
};

Here n is first constructed (without any default value), then int() causes a temp int to be created with value 0 Which is then assigned to n;

Upvotes: 1

James Hopkin
James Hopkin

Reputation: 13973

No, the variable is only left uninitialised in the first case.

For a member that is a class with a user-defined constructor, the situation is simple: a constructor is always called.

Built-in types (and 'plain old data' structs) may be left uninitialised, as in your first example. Although they don't have user-supplied constructors, using the construction syntax (your other two examples) initialises them to zero.

The reason for this slightly tricky rule is to avoid undue overhead; for example if you defined:

struct S
{
   int array[1024*1024];
};

with the intention of only assigning values as you needed them, you wouldn't want the compiler to whitewash 4Mb of memory with zeroes whenever you construct one.

Upvotes: 1

xian
xian

Reputation: 4693

You might find this interesting.

The difference between new Foo and new Foo() is that former will be uninitialized and the latter will be default initialized (to zero) when Foo is a POD type. So, when not using the form with the parens, the member "a" can contain garbage, but with the parens "a" will always be initialized to 0.

Upvotes: 3

anon
anon

Reputation:

I'm afraid you are wrong. When you say:

int n = int();

Then n (and all other POD types) will zero initialised.

Also, make sure that you are very clear in your mind about the difference between initialisation and assignment - this is quite important in C++:

int n = int();    // initialisation
n = 0;            // assignment

Upvotes: 4

Related Questions