Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

class B derived from an abstract base class A, and how can i use singleton in class B?

below is the demo code:

class A {
public:
    A(){}    
    virtual void method()=0;
    //....
    virtual ~A(){};
}

class B : public A{
    static A * ptr;
    //....
public:
    //....
    static A* GetInstance() {
        if (ptr == nullptr)
            ptr = new B();  // error, currently B is an abstract class, it has not been constructed
        return ptr;
    }
    //.....
}

class B derived from an abstract base class A, and how can i use singleton in class B?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to implement your method1 inside class B.
This is not a problem of Singleton. The problem is, that you cannot create an instance of an abstract class. Your class B is abstract, because not all pure virtual methods are implemented in class B.

Or do the following:

class AImplement : public A

Inside AImplement, you implement your method1, so that AImplement becomes not abstract.

Now, you can create AImplement inside class B.

And do not derive B from A.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading