what is the order of initialization for data?
Answer Posted / sachin magdum
Kasi, I am not agreed with you, in your case sal will be initialized before ssn.
Debug this program and see,
class A
{
int i ;
public :
A (int _i)
{
i = _i;
}
};
class B
{
A a;
A b;
A c;
public :
B(int _a, int _b, int _c) : a(_a), c(_c), b(_b)
{}
};
int main(int argc, char* argv[])
{
B b(1,2,3);
return 0;
}
Here the initialization order is first 'a' then 'c' and then 'b' and not a, b, c.
However, if you have base class then the case is little different
class A
{
int i ;
public :
A (int _i)
{
i = _i;
}
};
class B : public A
{
A a;
A b;
A c;
public :
B(int _a, int _b, int _c, int _base) : a(_a), c(_c), b(_b), A(_base)
{}
};
int main(int argc, char* argv[])
{
B b(1,2,3,4);
return 0;
}
In this case first 'A' that is base class of B, then 'a' then 'c' then 'b' will be initialized.
If you have multiple base classes, then they will be initialized in the order of their declaration, and not in the order how they are initialized.
class A
{
int i ;
public :
A (int _i)
{
i = _i;
}
};
class C
{
int i ;
public :
C (int _i)
{
i = _i;
}
};
class B : public A, public C
{
A a;
A b;
A c;
public :
B(int _a, int _b, int _c, int _baseA, int _baseC) : a(_a), C (_baseC), c(_c), b(_b), A(_baseA)
{}
};
int main(int argc, char* argv[])
{
B b(1,2,3,4,5);
return 0;
}
In this case first 'A' then 'C' then 'a' then 'c' and then 'b' will be initialized.
Is This Answer Correct ? | 3 Yes | 1 No |
Post New Answer View All Answers
How do you establish an is-a relationship?
What is the best way to take screenshots of a window with c++ in windows?
Why is c++ so fast?
Who discovered c++?
What is split a string in c++?
What does new do in c++?
What problems might the following macro bring to the application?
How are Structure passing and returning implemented by the compiler?
Can we declare a base-class destructor as virtual?
What is virtual base class?
Show the declaration for a static function pointer.
Can manipulators fall in love?
What is nested class in c++?
What is the difference between cin.read() and cin.getline()?
Is sorted c++?