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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With