Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to initialize a simple class without a constructor?

Tags:

c++

I have a very simple class, like this:

class MySimpleClass
{
public:
    uint16_t   m_myInt;
    String     m_myString;
    String     m_myOtherString;
    MyEnum     m_myEnumValue;
    bool       m_myBool;
};

This class is part of a pre-compiled library that I can't change, and it doesn't offer a constructor. Is there any way that I can initialize this class without having to do something like this...

MySimpleClass msc;
msc.m_myInt = 1;
msc.m_myString = "foo";
msc.m_myOtherString = "bar";
msc.m_myEnumValue = ENUM_VALUE_YES;
msc.m_myBool = true;

I'm not averse to doing it that way, but I'm curious to know if there's some kind of initialization syntax that will do it?

I'm working in C++03, but answers in C++11 will be of interest as well.

like image 251
Karl Nicoll Avatar asked Sep 09 '25 16:09

Karl Nicoll


2 Answers

You can add a free function that you can use as a constructor:

MySimpleClass make_msc(
    uint16_t myInt,
    String myString,
    String myOtherString,
    MyEnum myEnumValue,
    bool myBool)
{
    MySimpleClass msc;
    msc.m_myInt = myInt;
    msc.m_myString = myString;
    msc.m_myOtherString = myOtherString;
    msc.m_myEnumValue = myEnumValue;
    msc.m_myBool = myBool;
    return msc;
}

//Usage:
MySimpleClass msc = make_msc(1,"foo","bar",ENUM_VALUE_YES,true);

Alternatively, you can use aggregate initialisation:

MySimpleClass msc = {1,"foo","bar",ENUM_VALUE_YES,true};//C++03 or C++11
MySimpleClass msc{1,"foo","bar",ENUM_VALUE_YES,true}; //C++11 only

Note: The

MySimpleClass msc = {1,"foo","bar",ENUM_VALUE_YES,true};

form can only be used in a declaration, but the:

MySimpleClass{1,"foo","bar",ENUM_VALUE_YES,true}
make_msc(1,"foo","bar",ENUM_VALUE_YES,true)

forms can be used in any expression that expects a MySimpleClass.

like image 141
Mankarse Avatar answered Sep 14 '25 17:09

Mankarse


Uniform initialization in C++11 is useful

MySimpleClass x {1, "foo", "bar", NUM_VALUE_YES, true};
like image 40
masoud Avatar answered Sep 14 '25 16:09

masoud