views:

64

answers:

3

Hi, declaring a struct Table:

struct Tables {
       int i;
       int vi[10];
       Table t1;
       Table vt[10];
};

Tables tt;

assuming that a user-deault contructor is defined for Table.

here tt.t1 will be initialized using the default contructor for Table, as well as each element in tt.vt.

On the other hand tt.i and tt.vi are not initialized because those objects are not of a class type.

so we remain with a semi-initialized object tt.

if I understood well - if tt.i or tt.vi won't be explicitly initialized i the code, after creating tt, an error will be thrown if we try to read a value from them?

2) can someone explain it to me, why cpp designers didn't want to simply initialize the built-in types int and int[] to zero?

+4  A: 

No, no error will be thrown. You will have a mild case of undefined behaviour. However, as integers don't have trap values, there is no way the behaviour can be detected.

Note that the C++ language itself throws exceptions only very, very rarely - about the only times I can think of where it does it is when performing an invalid cast to a reference via dynamic_cast, and when new fails to allocate. Of course the Standard Library may throw in a number of error conditions.

As to why C++ works that way (and C too), well initialisation takes time, and if it is not needed that is time wasted. For example, if you were going to read user input immediately into those variables, there is little point in initialising them before you do so.

anon
but I thought `dynamic_cast` never throws any error? I believe that if the types are not compatible then the returned pointer will just be `null`.
phunehehe
@phunehehe It throws when casting to a *reference*.
anon
thanks Nell, I didn't know that.hmm but I guess I'd just use the pointer cast.
phunehehe
+3  A: 

An error won't be thrown, this isn't Java. :)

What will be returned will be whatever happens to be in the memory at that time. What you have is an "uninitialized" variable. It might be 0. It might be 42. It will be something unpredictable every time.

Moral of the story - initialize ALL of your variables. Failure to do so can cause incredibly difficult bugs down the road.

Since this is C++, use a default constructor to initialize your struct:

struct Tables { 
       int i; 
       int vi[10]; 
       Table t1; 
       Table vt[10]; 

Tables() {
  i = 0;
  for (int iter = 0; iter < 10; iter++)
    vi[iter] = 0;
}

}; 

Tables tt; 
Starkey
Strictly speaking, that does not initialise them - it assigns to them. whether or not this is a good idea depends on what the user is going to do with them.
anon
+1  A: 

Since they are not pointer types, they will be populated with whatever is on the stack at that location. If they were pointer types and you dereferenced them without properly initializing them, then yes you would have issues.

David