0

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?

FLYFLY
  • 49
  • 6
  • Tactical note: Look at the [Meyers Singleton](https://stackoverflow.com/a/1008289/4581301) for a safer and generally easier way to implement a singleton. But think more on whether or not you want a singleton. It's basically a global variable wrapped in a class, and global variables tend to complicate code in the guise of simplifying it. You have to manage the fact that anyone can alter the global at any time with little traceability; when debugging everything could have unannounced side effects.. – user4581301 Dec 11 '21 at 07:54

1 Answers1

0

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.

eberhard
  • 86
  • 4