Almost always, in examples of code, I encountered initialization of class fields outside the body of the constructor:

MyClass(): a(1),b(2),c(3) { } 

but not

 MyClass() { a = 1; b = 2; c = 3; } 

If both options are working, what is the practical use of initialization outside the body of the constructor?

    2 answers 2

    In the first case, you are calling the constructors for the fields, and thereby initializing the fields.

    In the second case, you first call the default constructors, and if field initializers are missing in their definition, then copy assignment operators are also called to initialize these fields accordingly, which can be very expensive in the end.

    Imagine, for example, that memory is dynamically allocated in a constructor. Then this memory will be redefined in the copy assignment operator.

    In addition, it may happen that some data member does not have a default constructor at all, but only constructors with parameters. In this case, the second option will not compile at all.

    Consider a simple example.

    This program will compile successfully.

     #include <iostream> struct A { int x; A( int x ) : x( x ) {} }; struct B { A a; B() : a( 10 ) {} }; int main() { return 0; } 

    However, the following program will not compile

     #include <iostream> struct A { int x; A( int x ) : x( x ) {} }; struct B { A a; B() { a = 10; } }; int main() { return 0; } 

    because there is no default constructor for class A , which must be called before transferring control to the body of constructor B

      In the order of the call.

      First, the class fields are initialized in the list of initialization (option 1). If there is no list, the compiler will make it himself in the order in which the fields are declared in the class. Then there will be what is written in the body of the constructor (option 2).

      For your particular example, no difference, because you use simple data types. There is no additional overhead.

      It makes sense for classes that have objects of other classes as fields. In this way, the non-creation of a class object can be achieved if an error occurs during the initialization of some of its fields. Well, for objects of other classes may be the cost of initializing the object. Therefore, you may receive a second call. Well, the last argument - option 1 is a good practice.

      I think something else will add in the comments and other answers.