Home > Mobile >  C 11 - If I initialize a variable in a class header file, is a default constructor generated?
C 11 - If I initialize a variable in a class header file, is a default constructor generated?

Time:07-20

Here is a short example of a class with a variable myInteger which is not initialized in the single constructor which has been defined.

// A.h

class A
{
    public:
        
    A(const std::string& str);

    private:

    int myInteger;
};


// A.cpp

A::A(const string& str)
{
    // I do something with str
}

A single constructor is defined, which means that the compiler will not generate a default constructor with no arguments.

  • Question: If the header file is changed so that the variable myInteger is set to a value, does the compiler generate a new default constructor?
// A.h

class A
{
    public:
        
    A(const std::string& str);

    private:

    int myInteger = 3;
};
  • Question: If the header file is changed so that the variable myInteger is set to a value, does the compiler modify the behavior of the constructor defined above to be like the following?
A::A(const string& str)
    : myInteger{3}
{
    // I do something with str
}

I checked Effective Modern C for an answer to this question but couldn't find it in there. It is a bit of an unusual question.

CodePudding user response:

Question: If the header file is changed so that the variable myInteger is set to a value, does the compiler generate a new default constructor?

No. cppreference gives you some hint:

3 Implicitly-declared default constructor
If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

If some user-declared constructors are present, the user may still force the automatic generation of a default constructor by the compiler that would be implicitly-declared otherwise with the keyword default. (since C 11)

There is no reasoning about how the members look like, only if other constructors are present. And in your case the other constructor is still present.

Question: If the header file is changed so that the variable myInteger is set to a value, does the compiler modify the behavior of the constructor defined above to be like the following?

Yes. See also cppreference

  1. Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

Default member initializers are quite valuable. You write the initial value once and it is applied automatically in every constructor (that does not provide its own member initializer). It would even be applied in an implicitly declared/defined default constructor (which you don't have in your example).

  •  Tags:  
  • c 11
  • Related