6

Possible Duplicates:
C++ weird constructor syntax
Variables After the Colon in a Constructor
What does a colon ( : ) following a C++ constructor name do?

For the C++ function below:

cross(vector<int> &L_, vector<bool> &backref_, vector< vector<int> > &res_) : 

    L(L_), c(L.size(), 0), res(res_), backref(backref_) {

    run(0); 

}

What does the colon (":") tell the relationships between its left and right part? And possibly, what can be said from this piece of code?

Community
  • 1
  • 1
luna
  • 133
  • 2
  • 7
  • Voting to close as a duplicate but the title of the original question leaves a lot to be desired. Should it be edited perhaps? – Troubadour Aug 17 '10 at 15:54
  • 3
    I don't see a major problem with the title of the 'weird syntax' question. The real problem with both questions is that once you know to search for "initializer list" your problem has already been solved. I think keeping 'constructor' in the title is helpful, though. A `:` is almost unsearchable in any case; perhaps spelling it `colon` would help, I don't know. – CB Bailey Aug 17 '10 at 16:20

3 Answers3

5

This is a way to initialize class member fields before the c'tor of the class is actually called.

Suppose you have:

class A {

  private:
        B b;
  public:
        A() {
          //Using b here means that B has to have default c'tor
          //and default c'tor of B being called
       }
}

So now by writting:

class A {

  private:
        B b;
  public:
        A( B _b): b(_b) {
          // Now copy c'tor of B is called, hence you initialize you
          // private field by copy of parameter _b
       }
}
John
  • 15,990
  • 10
  • 70
  • 110
Artem Barger
  • 40,769
  • 9
  • 59
  • 81
4

It's a member initialization list.

You're setting each of the member variables to the values in parentheses in the part after the colon.

John
  • 15,990
  • 10
  • 70
  • 110
3

Like many things in C++, : is used for many things, but in your case it is the start of an initializer list.

Other uses are for example after public/private/protected, after a case label, as part of a ternary operator, and probably some others.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636