Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the colon mean in a constructor? [duplicate]

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?

like image 793
luna Avatar asked Aug 17 '10 15:08

luna


People also ask

What Does a colon mean in CPP?

Two colons (::) are used in C++ as a scope resolution operator. This operator gives you more freedom in naming your variables by letting you distinguish between variables with the same name.

What does colon mean in for loop C++?

Colon ':' is basically a operator which indicates that the y is inside x and assign the y's value to the elements of array one by one.

How does a constructor work in C++?

A constructor in C++ is a special 'MEMBER FUNCTION' having the same name as that of its class which is used to initialize some valid values to the data members of an object. It is executed automatically whenever an object of a class is created.

Why do we use initializer list in C++?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.


1 Answers

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
       }
}
like image 114
Artem Barger Avatar answered Sep 23 '22 12:09

Artem Barger