0

Possible Duplicate:
What does a colon following a C++ constructor name do?
Class construction with initial values

I saw code that looked like this:

class Demo
{
    Joystick joystick;

public:
    Demo(void):
        joystick(1)  // The first USB port
    {
        /* snip */
    }
};

Joystick is being initialized before the bracket in the constructor. What does it mean when you do that? What is this called? I'm assuming it differs in some way then initializing joystick inside the bracket -- in what ways does it differ?

Community
  • 1
  • 1
Michael0x2a
  • 58,192
  • 30
  • 175
  • 224

1 Answers1

1

It is called an initializer list, and it does differ from initializing inside the body of the constructor.

You can call the constructors of every data member in the class in the initializer list. Also you can call a custom parent class(s) constructor within it, if you didn't, every data member or parent class you don't initialize with the initializer list will be initialized with its default constructor, if it doesn't have, you will see a compiler error.

This is an extended example:

class Parent
{
bool b;
public:
    Parent(bool B): b(B)
    {
    }
};

class Child: public Parent
{
    int i;
    double d;
public:
    Child(int I, double D, bool B): i(I), d(D), Parent(B)
    {
    }
};

For the order they are called, see this question and this question.

In fact explaining it is an entire article as it's a basic and important thing in classes, just try Googling it and reading some results.

Community
  • 1
  • 1
Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82