×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: C++
Posted by: Jose Canedo
Added: Feb 6, 2017 3:09 PM
Views: 13
Tags: no tags
Initialization order can F&*# up your app.
  1. // Example program
  2. #include <iostream>
  3. #include <string>
  4.  
  5. class someClass
  6. {
  7. public:
  8.     someClass():
  9.         A(5),      
  10.         B(A*5), //this might look ok, but it is not. A is used before initialization [-Wreorder]
  11.         C(A){}; //this order here means nothing, so B and C will have unpredictable values
  12.        
  13.     void printMembers()
  14.     {
  15.         std::cout << "A: " << A << std::endl;
  16.         std::cout << "B: " << B << std::endl;
  17.         std::cout << "C: " << C << std::endl;
  18.     };    
  19. private:
  20.     int C;  
  21.     int B;
  22.     int A; //this stablishes the initialization order: C, then B, then A.
  23. };    
  24.  
  25. int main()
  26. {
  27.     someClass a;
  28.     a.printMembers();
  29. }
  30.