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
Is c better than c++?
Explain the difference between abstract class and interface in c++?
What is a multimap c++?
What is namespace & why it is used in c++?
What is pointer to array in c++?
Must accepts "Maestro Cards" Tax for bike should be less than 15 Total number of lanes is more than 10 Must provides monthly pass Write a method: boolean isGoodTollBridge(String[] cardsAccepted, String[] tollTax, boolean hasMonthlyPass, int numberOfLanes); String[] cardsAccepted A String array of names of card types accepted for payment of toll tax, it can be null if the toll does not accept any card String[] tollTax A String array of toll tax chart (say “Train : 300â€Â,â€ÂBullCart : 10â€Â) boolean hasMonthlyPass This parameter defines whether there is any monthly pass available or not int numberOfLanes This parameter defines the number of lanes for each side
What are the basic data types used in c++?
Is map thread safe c++?
How do you flush std cout?
Write a recursive program to calculate factorial in c++.
What is the use of namespace std in C++?
Which software is best for coding?
Show the declaration for a pointer to function returning long and taking an integer parameter.
What does std :: flush do?
What is difference between array and vector in c++?