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
What is const in c++?
Explain the concept of friend function in c++?
What are signs of manipulation?
Which is the best c++ software?
Which sort is best for the set: 1 2 3 5 4 a) Quick Sort b) Bubble Sort c) Merge Sort
Is c++ free?
What are the advantages of prototyping?
How the virtual functions maintain the call up?
what is C++ objects?
What is exception handling? Does c++ support exception handling?
What is & in c++ function?
If there are two catch statements, one for base and one for derived, which should come first?
Do inline functions improve performance?
What do you mean by delegate? Can a user retain delegates?
Are vectors passed by reference c++?