0

im new in c++

my problem: this is my singleton:

class Singleton
{
    static Singleton *singletonInstance;
    Singleton() {}

    public:
    int numero = 0;

    static Singleton* getSingletonInstance()
    {
        //std::lock_guard<std::mutex> lock(m_);
        if(singletonInstance == nullptr)
        {
            singletonInstance = new Singleton();
        }
        return singletonInstance;
    }
};

this is another file .cpp where i set or get the "numero" variable:

Singleton.getSingletonInstance()->numero = 10;

I get this error:

error: expected unqualified-id before '.' token

Singleton.getSingletonInstance()->numero = 10;

How do to set "numero" variable and get/set the numero from sigleton in/from other class .cpp ? My target is use this singleton. I'm new in c++. Where I wrong ? Thanks

Community
  • 1
  • 1
Mr. Developer
  • 3,295
  • 7
  • 43
  • 110

1 Answers1

2

The symbol Singleton is not an object, it's a class. For that you have to use the scoping operator :::

Singleton::getSingletonInstance()->numero = 10;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • error: undefined reference to 'Singleton::singletonInstance', maybe I should rewrite singleton class ? – Mr. Developer Jun 14 '17 at 13:50
  • getSingletonInstance @Some programmer dude – Mr. Developer Jun 14 '17 at 13:51
  • @Mr.Developer You will have to define `Singleton Singleton::*singletonInstance = nullptr` in your source somewhere , I guess – P0W Jun 14 '17 at 13:52
  • @Mr.Developer That's a problem for another question actually. And that question have been answered *many* times . [For example here](https://stackoverflow.com/questions/272900/undefined-reference-to-static-class-member). – Some programmer dude Jun 14 '17 at 13:52
  • @P0W: It should be: `Singleton Singleton::singletonInstance = nullptr;` without the `*`. You have to define that after your class in your `class.cpp` – Andre Kampling Jun 14 '17 at 13:53
  • @AndreKampling No the instance variable is declared as a pointer so the definition needs to be one too. But the asterisk should be moved. – Some programmer dude Jun 14 '17 at 13:55
  • 1
    @Someprogrammerdude: Yeah you're right. Where was my head...? It has to be: `Singleton* Singleton::singletonInstance = nullptr;` – Andre Kampling Jun 14 '17 at 13:57
  • @Mr.Developer: You have to define your static variable additionally after the class like this: `class Singleton { ... }; Singleton* Singleton::singletonInstance = nullptr;` – Andre Kampling Jun 14 '17 at 14:02