In a class that looks somehow like this:
MyClass.h
class MyClass{
public:
MyClass();
int x1;
int x2;
int x3;
int x4;
int x5;
private:
int y1;
int y2;
};
MyClass.cpp
#include "MyClass.h"
int someFunc1(int x1, int x2){
return x1+x2;
}
int someFunc2(int x1, int x2){
return x1+x2;
}
MyClass::MyClass():
x1(1), x2(2), x3(3), x4(4),
y1(someFunc1(x1, x2)), y2(someFunc2(x3, x4)), x5(y1+y2){}
main.cpp
#include "MyClass.h"
int main(int argc, char **argv)
{
MyClass myclass;
return 0;
}
Compiler's outputs:
In file included from MyClass.cpp:1:
MyClass.h: In constructor ‘MyClass::MyClass()’:
MyClass.h:13:9: warning: ‘MyClass::y2’ will be initialized after [-Wreorder]
int y2;
^~
MyClass.h:9:9: warning: ‘int MyClass::x5’ [-Wreorder]
int x5;
^~
MyClass.cpp:11:1: warning: when initialized here [-Wreorder]
MyClass::MyClass():
^~~~~~~
MyClass.cpp: In constructor ‘MyClass::MyClass()’:
MyClass.cpp:13:54: warning: ‘*<unknown>.MyClass::y1’ is used uninitialized in this function [-Wuninitialized]
y1(someFunc1(x1, x2)), y2(someFunc2(x3, x4)), x5(y1+y2){}
^~
MyClass.cpp:13:57: warning: ‘*<unknown>.MyClass::y2’ is used uninitialized in this function [-Wuninitialized]
y1(someFunc1(x1, x2)), y2(someFunc2(x3, x4)), x5(y1+y2){}
^~
I'm not in control of someFunc1
and someFunc2
, I just defined them in that way to get the code compiled.
I can fix these warnings by getting rid of member-initializer list, and initialize the data members in constructor's body like this:
MyClass::MyClass(){
x1 = 1;
x2 = 2;
x3 = 3;
x4 = 4;
y1=someFunc1(x1, x2);
y2=someFunc2(x3, x4);
x5=y1+y2;
}
Or I can reorder the declaration of data members in class body like this:
class MyClass{
public:
MyClass();
int x1;
int x2;
int x3;
int x4;
private:
int y1;
int y2;
public:
int x5;
};
But here I'm declaring a scope of public members unnecessarily twice!
How to fix (not get rid) of these warnings and still use member-initializer list for initialization?
As you can see the data members in the first original form are defined in a correct order according to their usages, but the compiler still can't figure out that itself.