I have the following class
#include <string>
class A {
protected:
std::string m1;
int port;
public:
std::string m2;
A(std::string,std::string,int);
};
A::A(std::string _m1,std::string _m2,int _port) : m1(_m1),m2(_m2),port(_port){
}
int main(int argc, char *argv[]){
A("x","y",argc);
}
when compiled with gcc ARM 5.40 and -Wreorder
it outputs
a.cpp: In constructor ‘A::A(std::__cxx11::string, std::__cxx11::string, int)’:
a.cpp:9:16: warning: ‘A::m2’ will be initialized after [-Wreorder]
std::string m2;
^
a.cpp:6:8: warning: ‘int A::port’ [-Wreorder]
int port;
^
a.cpp:15:1: warning: when initialized here [-Wreorder]
A::A(std::string _m1,std::string _m2,int _port) : m1(_m1),m2(_m2),port(_port){
^
Why does it generate the warning ?
Will
m2
andport
have default value or value assigned inmain
?Why it does not happen with
m1
?Is this a correct way to initialize member variables ?
In C++ member are initialized in the order they appear in the class, not the order you initialize them in the member initializer list. That means that the order in this case is
m1, port, m2
and notm1, m2, port
like you have in the initializer list. This is important because if you use one member to initialize another you need to make sure that member is declared first in the class otherwise you use an uninitialized value and that is undefined behavior.