What's the difference between initializing a variable in these constructors? And how to put a constructor as default?

1

Is there any difference in initializing a variable in any of these forms of constructors? And how do I put a constructor as default ( default ) in a class that has more than one constructor?

Builder 1:

class Teste
{
private:
    int valor1, valor2;
    float valor3;
public:
    Teste(void) : valor1(0), valor2(0), valor3(0.f) {}
};

Builder 2:

class Teste
{
private:
     int valor1, valor2;
     float valor3;
public:
     Teste(void)
     { 
         valor1 = 0;
         valor2 = 0;
         valor3 = 0.f;
     }
};

I am currently preferring to use constructor method 1 because I find it cleaner, changes into something?

    
asked by anonymous 30.10.2017 / 15:04

1 answer

1

In this particular case nothing changes. I recommend the first only to leave uniform with cases that need to do so.

In cases of having members that need to be initialized and are classes there will be creation of a temporary object of the value and then copied to the variable and this is inefficient. It worsens if the member type has a default constructor.

If a member is declared as const the only way to initialize it is as in the first example, using boot list (the name of this).

FAQ .

The default constructor is a parameterless constructor.

You do not need to use void to empty the parameters in C ++.

    
30.10.2017 / 15:23