code generating wreorder warning

994 views Asked by At

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){
 ^
  1. Why does it generate the warning ?

  2. Will m2 and port have default value or value assigned in main ?

  3. Why it does not happen with m1 ?

  4. Is this a correct way to initialize member variables ?

1

There are 1 answers

0
NathanOliver On BEST ANSWER

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 not m1, 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.