0

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?

  • possible duplicate of [What is the use of making constructor private in a class?](http://stackoverflow.com/questions/2062560/what-is-the-use-of-making-constructor-private-in-a-class) – paulsm4 Jun 23 '12 at 16:47

1 Answers1

2

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

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    Yes, I know that. My doubt is about inheritance. Thank you so much. –  Jun 23 '12 at 16:47
  • Typically they also have their copy constructor, assignment operator and destructor declared private as well. Most of the Singletons in C++ I've seen only return a reference or a pointer to the class. – Mike Bailey Jun 23 '12 at 16:47