Danil Prokhorenko
Danil Prokhorenko

Reputation: 1104

Can I create singleton child class?

I have a parent class:

class ParentClass {
public:
    ~ParentClass(){}
    static ParentClass &getInstance() {
        static ParentClass instance;
        return instance;
    }

    void methodA() {
        //do some stuff
    }

    void methodB() {
        //do some stuff
        methodA();
        //do some stuff
    }

private:
    ParentClass(){}
}

I want to create child class:

class ChildClass : public ParentClass {
public:
    ChildClass(){}
    ~ChildClass(){}

    methodA() {
        //do some stuff
    }
}

This code have some obvious problems. First of all I can't create ChildClass in this way (parent's constructor is private). And seems like ChildClass can't directly inherited from ParentClass. These classes are very similar. And I do not want to create two similar copies of these classes.

Probably I can create one base class for ParentClass and ChildClass. I'm not sure but does some method exist for creating childs from singleton?

Upvotes: 1

Views: 2022

Answers (1)

Alex Lop.
Alex Lop.

Reputation: 6875

Singleton has a well defined target. It has to make sure that only a single instance of the given type exists in the current environment.

Thus I don't see any good reason to have methodA and methodB are inside it. Especially that no one can create an object of type ParentClass and thus cannot call methodA and methodB (unless they also become static). I think a better OOD would be to create the singleton only with getInstance() method and separately create ParentClass which would contain a reference to the object which is returned by the singleton:

class SingletonClass {
public:
    ~SingletonClass (){}
    static SingleInstanceClass &getInstance() {
        static SingleInstanceClass instance;
        return instance;
    }

private:
    SingletonClass (){}
}

class ParentClass {
public:
    ParentClass(SingleInstanceClass& ref);
    ~ParentClass(){}

    virtual void methodA() {
        //do some stuff
    }

    void methodB() {
        //do some stuff
        methodA();
        //do some stuff
    }

private:
    SingleInstanceClass& singInstRef;
}

And then

class ChildClass : public ParentClass {
public:
    ChildClass(SingleInstanceClass& ref) : ParentClass (ref){}
    ~ChildClass(){}

    virtual void methodA() {
        //do some stuff
    }
}

Upvotes: 1

Related Questions