Skip to main content
1 of 7

A Singleton Base and derived class

  1. The reason I am not creating a static object is because I need to have the ability to delete the created concrete object.

  2. I have an base and derived class since, I need to have different kinds of concrete classes.

  3. I cannot use the getInstance() function in the base class since I cannot make it both static and virtual

class ITrafficEventsReturner {

public: virtual ~ITrafficEventsReturner() {} ;

protected:

ITrafficEventsReturner() { };

// no definition for copy constructor and assignment operator
ITrafficEventsReturner(const ITrafficEventsReturner&);
ITrafficEventsReturner& operator=(const ITrafficEventsReturner&); };

class ConcreteTrafficReturner : public ITrafficEventsReturner {

public: static ConcreteTrafficReturner* getInstance() { if (myself == 0) { myself = new ConcreteTrafficReturner(); }

  return myself;    }

~ConcreteTrafficReturner() { if (myself) { delete myself; myself = 0; } }

private : ConcreteTrafficReturner() : ITrafficEventsReturner() {

};

static ConcreteTrafficReturner* myself; };

static ConcreteTrafficReturner* ConcreteTrafficReturner::myself = 0;

ConcreteTrafficReturner* ConcreteTrafficReturner::myself = 0;

int main() { ITrafficEventsReturner* ConcreteTrafficReturner = ConcreteTrafficReturner::getInstance();

delete ConcreteTrafficReturner; };