-1

I've downloaded simple code with constructors. Could anyone explain me this part of code:

class Myclass
{
private:
    int x;
    double *y;                      

public:
    Myclass(int X);              

};

Myclass::Myclass(int X) : x(X)
{
y = new double[x];
}

I don't understand "Myclass::Myclass(int X) :x(X)". Couldn't it be written simpler?

Adam Madamski
  • 21
  • 1
  • 5

2 Answers2

4

I guess from the bold face that it's just the : x(X) part you don't understand.

That's the initialiser list, used to initialise member variables. In this case, it initialises the variable x to have the same value as the constructor parameter X. y is not included in the list, so it's left uninitialised at that point, then assigned a value in the constructor body.

There's no simpler way to initialise a member variable (in a class with a non-trivial constructor).

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
4

You can't write it any simpler without altering the effect of the code.

You could write it this way:

Myclass::Myclass(int X)
{
    x = X;
    y = new double[x];
}

But then it wouldn't be an initialization of x, it would be an assignment to x.

Each member variable is initialized before running the constructor body (the part between { and }), in the so-called member initialization list between the : and the {.


As a side note, it would be better to initialize y in the member initialization list as well, rather than assigning to it in the constructor body:

Myclass::Myclass(int X) : x(X), y(new double[x])
{
}
Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • 3
    Try declaring the member as "const int x;", and then you'll see the difference between initialization and assignment. – Dan Korn Apr 15 '15 at 16:27