c++c++11default-valuestatic-members

C++ get default value of class member without creating new object


Let's consider definition:

struct ClassWithMember
{
    int myIntMember = 10;
}

I'd like to get myIntMember's default value, but do not create another instance of the class

// IMPOSSIBLE int myInt = ClassWithMember::myIntMember;  
// MUST AVOID int myInt = ClassWithMember().myIntMember;

I know workaround, but dislike it:

struct ClassWithMember
{
    static const int myIntMember_DEFAULT = 10;
    int myIntMember = myIntMember_DEFAULT;
}
int myInt = ClassWithMember::myIntMember_DEFAULT;

Because it needs extra line. And I cannot define inline static pointers like static const int *const INTEGER11_DEFAULT = 0x100088855;, such pointers must be defined in .cpp file, in .hpp is only declaration. Many of my classes are header-only, so create excess .cpp for this value isn't good idea.

Here is the similar question for C#


Solution

  • I call this solution workaround

    struct ClassWithMember
    {
        static const int myIntMember_DEFAULT = 10;
        int myIntMember = myIntMember_DEFAULT;
    }
    int myInt = ClassWithMember::myIntMember_DEFAULT;
    

    For pointers it will look more complicated

    //.hpp
    struct ClassWithMember
    {
        static AnotherClass* const myMember_DEFAULT;  //=X; Assignment not allowed
        AnotherClass* myMember = myMember_DEFAULT;
    }
    //.cpp
    AnotherClass* const MyNamespace::ClassWithMember::myMember_DEFAULT = pAnotherInstance;
    //usage
    auto *my = ClassWithMember::myMember_DEFAULT;