I've a class following singleton approach, but where do i initialize class members if its constructor is private?
class MyClass
{
MyClass() {}; //constructor is private
MyClass(const MyClass&);
MyClass& operator=(const MyClass&);
public:
static MyClass& Instance()
{
static MyClass singleton;
return singleton;
}
};
You can initialize the class members in the constructor itself as usual, even be it private.
The constructor is private to the outside world, not to the static member function Instance()
. That means, the line static MyClass singleton
in Instance()
actually invokes default constructor, and that is valid, as Instance()
has access to private
members of the class!
In the constructor, that's what it's there for. It has full access to members.
Also, be aware that this is unsafe in a multi-threaded application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With