Possible Duplicate:
Constructor initialization-list evaluation order
While writing a C++ constructor for a class, why is it that the order of initialising the member fields should be the order in which they are declared?
Consider the following C++ code. On compiling with gcc (gcc -g -Wall foo.cpp) I get the Warning
g++ -g -Wall main.cpp
main.cpp: In constructor ‘myclass::myclass(int, int, int, int, int, int)’:
main.cpp:12: warning: ‘myclass::z’ will be initialized after
main.cpp:11: warning: ‘int myclass::y’
main.cpp:26: warning: when initialized here
Here is the code. In this, the member z
appears in the initialization list of the
constructor class before y
and throws the above warning.
#include <iostream>
#include <iomanip>
class myclass
{
public:
int x;
int y;
int z;
myclass(int num1, int num2, int num3, int num4, int num5, int num6);//constructor for the class
private:
int a;
int b;
int c;
};
myclass::myclass(int num1, int num2, int num3, int num4, int num5, int num6)
:x(num1),z(num3), y(num2), a(num4),b(num5),c(num6)
{}
int main(int argc, char *argv[])
{
myclass jimmy(23,34,56,67,89,91);
std::cout << jimmy.x << std::endl;
std::cout << jimmy.y << std::endl;
std::cout << jimmy.z << std::endl;
return 0;
}
Generally, the order of execution is from top to bottom and left to right. But a rare condition arises where this rule fails is when the initializer list is used in class. In the initializer list, the order of execution takes place according to the order of declaration of member variables.
Always write member initializers in a constructor in the canonical order: first, direct base classes in the order in which they appear in the base-specifier-list for the class, then nonstatic data members in the order in which they are declared in the class definition.
Member variables are always initialized in the order they are declared in the class definition.
Parameterized constructor of “Type” class is called to initialize: variable(a). The arguments in the initializer list are used to copy construct “variable” directly.
This may help,
Constructor initialization-list evaluation order
Please see AProgrammer's reply in the above,
"The reason for which they are constructed in the member declaration order and not in the order in the constructor is that one may have several constructors, but there is only one destructor. And the destructor destroy the members in the reserse order of construction." – AProgrammer Aug 7 '09 at 6:45
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With