Search code examples
c++constructorctor-initializer

Properties declared beside the constructor


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.


Solution

  • 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.