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 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.
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.
New!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With