mardi 19 juillet 2022

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

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.

Aucun commentaire:

Enregistrer un commentaire