Goldman Sachs Interview Question
Applications DevelopersCountry: United States
Interview Type: Phone Interview
d) undefined
because execution of initialization list will be done from left to right. so first
a(var2++)
this statement will execute & it will pass a garbage value of var2. Then
var2( d++)
this statement will execute & will initialize var2's value as 5.
So at the end
var1 will be having a garbage/undefined value
var2 will be having value 5.
execution of initialization list happens from left to right.
If we have 3 list argument like,
class B : public A {
int b, c;
public:
B(int x): b(x), c (++b), A(b++) {
printf("ctor of class B: %d\n", b, c);
}
}
First A(++b) will get called!, as it is base class constructor, then rest of the argument list will get called from left to right, i.e. b(x), then c(++b).
If we do not pass A(++b) in argument list of B(), then default constructor will be passed.
yeah you are right..... execution of initialization list happens from left to right.
But for the above code, garbage value will be assigned to the base class's variable var1.
the order of initialization is not left to right or right to left. Rather it is the order in which it is declared in the class.
either way, here base class get initalized first and so it's undef..
d)
- judy April 09, 2013the step of constructing the object obj1:
1. allocating space for obj1;
2. call the base-class (A) constructor to initialize the base-class parts of the obj1
3. initializing the member of derved-class (B): var2( d++) , a(var2++)
so before initializing B member, the A's constructor is called, at that moment, nothing is given to the 'var1' of A class