-5

I was trying this constructor code and got confused with how it works..

#include<iostream>
using namespace std;
class XYZ{
    int a,b;
    public:
        XYZ(int i, int j):a(i), b(a*j){}
        void show(){
            cout<<a<<"\t"<<b<<"\n";
        }
};
int main(){
    XYZ X(2,3);
    X.show();
    return 0;
}

it gives the expected results but,

#include<iostream>
using namespace std;
class XYZ{
    int b,a;
    public:
        XYZ(int i, int j):a(i), b(a*j){}
        void show(){
            cout<<a<<"\t"<<b<<"\n";
        }
};
int main(){
    XYZ X(2,3);
    X.show();
    return 0;
}

give unexpected result.

the only difference is int a,b and int b,a

and how XYZ(int i, int j):a(i), b(a*j){} works exactly?

Abhishek Sharma
  • 2,485
  • 1
  • 21
  • 35
  • 1
    One question per question please. I've told you that several times before. Also, after almost four years and 20 questions, could you consider getting into the habit of _properly formatting your posts_ please? Full stops, capital letters... Thanks. – Lightness Races in Orbit Apr 09 '16 at 18:36
  • Possible duplicate of [What's the point of g++ -Wreorder?](http://stackoverflow.com/questions/1828037/whats-the-point-of-g-wreorder) – iksemyonov Apr 09 '16 at 18:39
  • 1
    Use `-Wall` to catch this (`-Wreorder` is the required flag, to be more precise, but it's included in `-Wall`). – iksemyonov Apr 09 '16 at 18:40

2 Answers2

6

Well, you already spotted the difference. And it's quite an important one. Members of a class are initialized in the order in which they appear in the class definition, regardless of the order they appear in the constructor's member initializer list. And since the initialization of b depends on the value of a, it is important that a should be initialized first. That's why this works:

int a,b;

But this doesn't:

int b,a;

It would be better though(much less error prone) if you write your constructor such that these dependencies don't exist. Then you don't have to worry about the order of declaration.

XYZ(int i, int j):a(i), b(i*j){}
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
5

On your second example, b is initialized before a. So b gets the result of evaluating a*j, where a is still uninitialized.

Barry
  • 286,269
  • 29
  • 621
  • 977
Markus
  • 3,155
  • 2
  • 23
  • 33