0

This is my first ever question posted on Stack Overflow, hope someone could explain it. So basically the two classes are the same except the order of the private member variables. The output is 10 20 10 0 I cannot understand why the order of declaration affects the output.

#include <iostream>
using namespace std;

class MyClass{
public:
    MyClass(int value): b(value), a(b * 2){
        cout << b << " " << a << " ";
    }
private:
    int b;
    int a;
};

class YourClass{
public:
    YourClass(int value): d(value), c(d * 2){
        cout << d << " " << c << " ";
    }
private:
    int c;
    int d;
};

int main(){
    MyClass obj(10);
    YourClass OBJ(10);
}
lionelmayhem
  • 61
  • 1
  • 6
  • 1
    Because [order matters](https://isocpp.org/wiki/faq/ctors#ctor-initializer-order) and you should get a warning about this: http://coliru.stacked-crooked.com/a/2dc06f1a6801bb90 – user1810087 Apr 26 '21 at 10:39
  • 3
    Class data members are initialized in the order of their declaration inside the class, not in the order you specify by constructor initializer list. For YourClass, c will be initialized before initialization of d, but it uses d, so basically you have undefined behavior when initializing c. – Karen Melikyan Apr 26 '21 at 10:41
  • _I cannot understand why the order of declaration affects the output._ This is simply because the C++ standard specifies so: http://eel.is/c++draft/class.base.init#13.3. – Daniel Langr Apr 26 '21 at 10:54
  • Thank you, now I understand it. – lionelmayhem Apr 26 '21 at 11:12

1 Answers1

0

Class members are initialized in the order of their declaration.

Initialization Order of Class Data Members

#include <iostream>

class MyClass{
public:
    MyClass(int value): b(value++), a(value++){
        std::cout << b << " " << a << " " << std::endl;
    }
private:
    int b;
    int a;
};

class YourClass{
public:
    YourClass(int value): b(value++), a(value++){
        std::cout << b << " " << a << " " << std::endl;
    }
private:
    int a;
    int b;

};

int main(){
    MyClass obj(10);
    YourClass OBJ(10);
}

Output:

10 11
11 10
Anubhav Gupta
  • 421
  • 5
  • 12