Search code examples
c++oopdesign-patternsinheritancesingleton

C++ Singleton class - inheritance good practice


In an existing project, I am to inherit a Controller class (MVC) declared as Singleton so as to define my own treatment. How to appropriately derive this Singleton class?

First, I expand on context and need for this inheritance.

The application that I am added to the existing software wants to use a MVC module that performs almost same task as the one I am willing to perform. It is using the same methods up to signature and slight modifications. Rewriting my own MVC module would definitively be duplication of code. The existing module is intrinsically oriented towards its application to another part of the software, and I cannot simply use the same module. But is written as a Model-View-Controller pattern where Controller is Singleton. I derived View already.

Second, I have doubt that I can classicaly derive Singleton class.

Calling constructor from inherited class would simply call getinstance() for parent class and fail to return an object from derived class (?).

Third, it's how I see some way to deal with. Please comment/help me improve!

I copy the whole Singleton class in a class I could call AbstractController. I derive this class twice. The first child is singleton and adopts the whole treatment of parent class. The second child is the Controller for my part of the application, with own redefined treatment.

Thanks!


Solution

  • I'm not sure I understand the situation you're dealing with fully, and whether or not it's possible or appropriate to derive from the singleton depends very much on how the singleton is implemented.

    But since you mentioned "good practice" there's some general points that come to mind when reading the question:

    1. Inheritance isn't usually the best tool to achieve code re-use. See: Prefer composition over inheritance?

    2. Using singleton and "good practice" generally do not go together! See: What is so bad about singletons?

    Hope that helps.