Search code examples
c++singletoninitializationmemberdefault-constructor

Private member for singleton class


I have a singleton class for which I need a private member. I want that member to be empty until I use my setter method to set the right data.

class PlaybackHelper{
private:
    PlaybackHelper();
    PlaybackHelper(PlaybackHelper const&);
    void operator=(PlaybackHelper const&);

    playback_type type;

    Note note;
public:
    void setPlaybackType(playback_type aType);
    static PlaybackHelper &getInstance();

};

Xcode is giving me an error in my implementation file (where I'm implementing my private constructor) saying that I should initialize my member:

PlaybackHelper::PlaybackHelper(){

}

error: Semantic Issue: Constructor for 'PlaybackHelper' must explicitly initialize the member 'note' which does not have a default constructor

I don't understand why I'm not able to do this (especially since it's not giving me any errors for the playback_type type; (enum) member which works the same way) Any ideas what I could do to leave my Note member empty until I'm ready to assign a value to it?


Solution

  • playback_type is a plain old data, thus lacking of initializing type simply leaves it as uninitialized; However, class Note's non-default constructor is defined, and thus its default constructor would not be generated automatically if you did not define it. To solve it, you could either

    1. initialize it with the parameters of (one of the) non-default constructors defined by you.

      PlaybackHelper::PlaybackHelper() : note(/*...*/) { }

    2. Define a default constructor for class Note