Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Singleton usage: compiler complains about private constructor

I know that there is a million questions and answers about Singletons out there but I just can't seem to find the solution to this. So running the risk of negative votes, here's my problem:

I want to use this singleton implementation from Andrei Alexandrescu' Modern C++ Design:

header:

class Singleton
{
    static Singleton& Instance();
  private:
    Singleton(){};
    Singleton(const Singleton&){};
    Singleton& operator=(const Singleton&){};
    ~Singleton(){};
};

implementation:

#include "s.hh"

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

test:

#include "s.hh"

int main(void)
{
    Singleton& single = Singleton::Instance();
    return 0;
}

Now,

$g++ A.cc s.cc  && ./a.out 
In file included from A.cc:1:0:
s.hh: In function ‘int main()’:
s.hh:3:19: error: ‘static Singleton& Singleton::Instance()’ is private
 static Singleton& Instance();
               ^
A.cc:6:42: error: within this context
  Singleton& single = Singleton::Instance();
                                      ^

What is wrong with that? I am stuck...

like image 527
steffen Avatar asked Dec 16 '22 12:12

steffen


1 Answers

By default, a class' members are private. To access your singleton, you need to make Singleton::Instance public:

class Singleton
{
  // here!
  public:
    static Singleton& Instance();

  private:
    Singleton(){};
    Singleton(const Singleton&){};
    Singleton& operator=(const Singleton&){};
    ~Singleton(){};
};

Note that this is not the constructor (as you said in your title), it's the static member function that is supposed to return a reference to the singleton.

like image 63
Daniel Frey Avatar answered Jan 18 '23 22:01

Daniel Frey