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

Time:12-12

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?

CodePudding user response:

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.

  • Related