Initialize members of global const class

  • I have a class which is made like this:

    class myClass{
    QString value1;
    QString value2;
    QString value3;
    QFont someFont;

    This class is available globally and should be used as a data structure to pass data around some other classes.
    Now I would like to create a global object of that class, that should never change, which serves as fallback to restore the application in case of failure of something. I thought I'd use a global const object:

    const myClass fallbackObject;

    (note: the object is actually created inside my own namespace, it's not really "global")
    But how do I initialize this object's members so that they contain useful data?
    I know I could have used a constructor, but unfortunately that will cause a few side effects in my code (it would make legal a call to a method in class of mine -which I don't want to allow-, a bit hard to explain, just trust me).

    Thank you in advance

  • try this:

    // myClass init

    static bool init = initFunction();

  • It's as same as the constructor method.
    Any other ideas?

  • Moderators

    If you're using C++11 capable compiler you can either use uniform initialization syntax:

    const myClass fallbackObject{ "value1", "value2", "value3", QFont("Verdana") };

    or the non-static data member initialization:

    class myClass{
    QString value1 { "value1" };
    QString value2 { "value2" };
    QString value3 { "value3" };
    QFont someFont { QFont("Verdana") };
    const myClass fallbackObject;

    In c++03 you can simply create a function that would return the fallback object:

    myClass getFallback() {
        myClass c;
        c.value1 = "value1";
        c.value2 = "value2";
        c.value3 = "value3";
        return c;
    const myClass fallbackObject = getFallback();

  • Thank you very much, Chris! The uniform initialization syntax looks just the right tool!

  • Yep,

    this is why they added in C++11 :D

Log in to reply