Properties declared next to the constructor

I am very new to C / C ++ and do not know what this method is called. But thatโ€™s why Iโ€™m trying to find the answer here. 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 the body, which method is called, and why it is done this way. Why not do it like this.

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

If anyone can help me, it will be great.

+3
source share
5 answers

This is a list of initializers . You can initialize member variables using the list of initializers after the constructor.

, -, . , . , - , .

+7

( ) . , .

+2

. ( ) ( , int).

+1
source

It is preferable to initialize items in the initializer list. In your case, it does not matter, but it is impossible to initialize int & as you did in the second code fragment. This is the only place where you can also pass arguments to your base class constructor.

+1
source

Also note that this pointer is available in the initializer list if it is used to refer to data fields or member functions only in BASE classes.

0
source

Source: https://habr.com/ru/post/1741027/


All Articles