fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct M1 {
  5. int m_i;
  6. M1 (int i) : m_i(i) { cout<<"ctor M1 "<<m_i<<"\n"; }
  7. };
  8.  
  9. struct M2 {
  10. int m_o;
  11. M2 (M1 &m) :m_o(m.m_i) { cout<<"ctor M2 "<<m_o<<"\n"; }
  12. };
  13.  
  14. class A {
  15. M1 m1;
  16. M2 m2;
  17. public:
  18. A(int i) : m2(m1), m1(i) { cout << "ctor A\n"; }
  19. };
  20. class B {
  21. M2 m2;
  22. M1 m1;
  23. public:
  24. B(int i) : m1(i), m2(m1) { cout << "ctor B\n"; }
  25. };
  26. int main() {
  27. cout << "If members are declared in the right order: the initialisation is as expected\n";
  28. A(1);
  29. cout << "If members are declared in the wrong order: the dependent element is constructed based on wrong value\n";
  30. B(2);
  31. // your code goes here
  32. return 0;
  33. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
If members are declared in the right order: the initialisation is as expected
ctor M1 1
ctor M2 1
ctor A
If members are declared in the wrong order: the dependent element is constructed based on wrong value
ctor M2 0
ctor M1 2
ctor B