Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there 2 times initialization when there is a constructor with default argument [duplicate]

My question is about how the member data with initializer get initialized where there is also a default argument in the constructor.

class InputPlay {

    public:
        InputPlay(std::string s = "test" ) : _s(s) {  };

    private:
        std::string _s = "default";
};

Question:

Is there are going to be 2 times initialization for the variable _s when the construct is called? aka the _s will be initialized by the string literal default and then replace by the default argument "test" in the constructor?

like image 653
SLN Avatar asked Nov 20 '18 15:11

SLN


People also ask

Can a default constructor take arguments?

Like all functions, a constructor can have default arguments. They are used to initialize member objects. If default values are supplied, the trailing arguments can be omitted in the expression list of the constructor.

How many arguments are in a default constructor?

The number of parameters passed in the default constructor is zero. No parameters can be passed in the default constructor. The answer to the above question is zero or no parameters.

Which variable is initialized more than once?

New!

How constructor solve the problem of initialization?

The constructors should be used to initialize member variables of the class because member variables cannot be declared or defined in a single statement. Therefore, constructors are used in initializing data members of a class when an object is created.


1 Answers

No, _s will only be initialized once. The in class initialization is syntactic sugar for synthesizing a member initializer. If you provide your own member initializer then the compiler will use that instead of synthesizing one for you from the in class initialization.

like image 140
NathanOliver Avatar answered Feb 01 '23 15:02

NathanOliver