views:

87

answers:

5

I am very very new to C/C++ and not sure what the method is called. But thats why I am here trying to find the answer. let me show you an example

MyClass::MyClass() : valueOne(1), valueTwo(2)
{
      //code
}

Where valueOne and valueTwo are class properties that are assigned values outside of the body, what method is this called and why is it done this way. Why not do it this way

MyClass::MyClass()
{
      valueOne = 1;
      valueTwo = 2
      //code
}

If anyone can help me out that will be great.

+6  A: 

That is an initializer list. You can initialize your member variables using an initializer list after the constructor.

By default the constructor will automatically create the objects that are member variables by calling their default constructors. By using an initializer list you can specify to use other constructors. Sometimes if your member variable has no constructor with no argument you have to use an initializer list.

Brian R. Bondy
+1  A: 

This is called an initialization list. It's done mainly for performance (with larger objects) or consistency (with built-in types like int).

David
+1  A: 

It is preferred to initialize members in the initializer list. In your case it doesn't matter, but it is not possible to initialize an int& the way you did in the second code fragment. It is the only place where you can pass arguments to your base class constructor as well.

Eddy Pronk
+1  A: 

Initialisation lists (the former style) are usually preferred for efficiency and performance reasons. Personally I prefer them for code readability reasons too since it separates simple initialisation from any complex logic in the constructor itself.

Dan Head
A: 

Also note, that the this pointer is accessible in the initializer list if used to reference data fields or member functions in the BASE classes only.

Chris Kaminski