1

I've build a singleton class based on the hit posted here.

I've extended it with a getMessage() function, that will retrive an internal dictionary message - the dictionary needs to be loaded only once on the whole application, that is the reason of the singleton.

My code:

Singleton.hpp

class Singleton {

public:

    static Singleton& getInstance();
    std::string getMessage(std::string code);

private:

    Singleton() {}; 
    Singleton(Singleton const&) = delete;
    void operator=(Singleton const&) = delete;
};

Singleton.cpp

Singleton& Singleton::getInstance()
{
    static Singleton instance;
    return instance;
}


std::string Singleton::getMessage(std::string code)
{
    /// Do something
    return "Code example.";
}

And the main code:

main.cpp

int main()
{
        Singleton* my_singleton;
        my_singleton = Singleton::getInstance(); **<-- ERROR HERE**

        cout << my_singleton->getMessage("a"); << endl

}

Main is giving me an error: Cannot convert 'Singleton' to 'Singleton*' in assignment

What is the correct way to "instantiate" the singleton and make use of the getMessage function.

Thanks a lot for helping...

2

2 Answers 2

6

what about you just call the function like this:

Singleton::getInstance().getMessage("a");

instead of assigning it to a variable.

Sign up to request clarification or add additional context in comments.

3 Comments

Doesn´work and doesn´t make sense that I cannot store it in a variable...I need to fix howto store it in a variable, not to avoid it...
Actually this gave me a hint on how to solve it... Singleton& my_singleton = Singleton::getInstance(); then my_singleton.getMessage("a");
@Mendez no need the reference: just type it as: Singleton::getInstance().getMessage("a"); if you want to short it use a macro: #define theSingleton Singleton::getInstance() and use it with the macro: theSingleton.getMessage("a");
2

You want to store a reference to your singleton, not a pointer.

Singleton& my_singleton = Singleton::getInstance();

4 Comments

Not worked. Compiler generated error 'singleton' declared as reference but not initialized and several others on Singleton code...
@Mendez You need to declare it and initialize in the same expression like in the code above
I'm using the exact same Singleton in my own code all the time, it should work. But i prefer to access it like @Christian (and with a dot instead of ->)
@Mendez Please see that my answer does work in this online example: tutorialspoint.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.