What is the difference between initializing a constructor or doing assignment inside the constructor?

4

What's the difference between the two examples below?

Should I also assign the value inside the constructor in this class even though I have initialized?

Example 1:

class sof{
   int teste;
public: 
   sof(int t) : teste(t){}
);

Example 2:

class sof{
   int teste;
public: 
   sof(int t){
    teste = t;
   }
);
    
asked by anonymous 02.12.2016 / 02:39

2 answers

3

In this example it is indifferent since int does not have a default constructor. The construction is done directly by the compiler in the assignment. It would be different if the type of member to be initialized was a type that has a default constructor.

Let's think of something like this:

class Tipo {
    int x;
public:
    Tipo() {
        x = 0;
    }
    Tipo(int p) {
        x = p;
    }
}

class sof {
    Tipo teste; //chama o construtor padrão
public: 
    sof(int t) {
        teste = Tipo(t); //chama o outro construtor
    }
};

class sof {
    Tipo teste; //não chama nada
public: 
    sof(Tipo t) : teste(t) {} //chama o construtor com parâmetro
};

This can be better checked in ideone or in CodingGround .

Note that if the default constructor does not exist, it has no option, the form of member initialization by list (the latter) is required.

Documentation .

Official FAQ .

    
02.12.2016 / 03:21
0

I would like to complete the previous answer with the following code:

#include <iostream>

class Tipo {
    int x;
public:
    Tipo() {
        x = 0;
        std::cout << "tipo-default\n";
    }
    Tipo(int p) {
        x = p;
        std::cout << "tipo-int\n";
    }
};

class sof {
    std::ostream& x;
    Tipo teste;
public:
    sof(int t) : x(std::cout << "sof\n") {
        std::cout << "sof-constr\n";
        teste = Tipo(t);
    }
};

int main() {
    sof s(10);
    return 0;
}

Here I show the case quoted by the previous answer and, furthermore, I show that the constructor of sof is not called in the execution of the class scope, but just before this constructor is called, as shown in the output: p>

sof
tipo-default
sof-constr
tipo-int

But it is also possible to see the other case of the member initializer lists which is the case of std::ostream& x : this must be declared and initialized in the "same statement" because it is a reference if it would be variables of type const ), then it can not be initialized in the constructor scope of sof .

    
20.06.2018 / 19:51