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;
}