Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 831
numerical25 Avatar asked Nov 23 '25 15:11

numerical25


2 Answers

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.

like image 128
Brian R. Bondy Avatar answered Nov 26 '25 03:11

Brian R. Bondy


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.

like image 20
Dan Head Avatar answered Nov 26 '25 03:11

Dan Head



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!