Search code examples
c++constructorprivateprivate-constructor

Subclass with private Constructor in C++


I've a simple question. Can a subclass have a private constructor (i.e. for singleton implementation) in C++?

class MySubClass : public MySuperClass {
public:
   // etc.
private:
    MySubClass();
    static MySubClass* _instance;
};

Is this example right?


Solution

  • Yes, that's how singletons are implemented in C++. The class also usually has a static method through which you can return an instance.