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

Question:

What is the difference between the two examples below?

Should I also assign the value inside the constructor in this class even though it was 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;
   }
);

Answer:

In this example it is indifferent since int does not have a default constructor. The construction is done directly by the compiler on assignment. It would be different if the type of the 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
};

See it working on ideone . And on repl.it. I also put it on GitHub for future reference .

Note that if there is no default constructor, there is no option, the initialization of member by list form (the latter) is required.

Documentation .

Official FAQ .

Scroll to Top