I am trying to write a singleton class with a static pointer as a member variable and also a map variable.
But if I use extern, in both the cases I get the error.
Here is the error.
In file included from animal_factory.cpp:1:0:
animal_factory.h:18:27: error: storage class specified for ‘factoryMap’
extern FactoryMap factoryMap;
^~~~~~~~~~
animal_factory.h:19:38: error: conflicting specifiers in declaration of ‘animalFactory’
extern static AnimalFactory *animalFactory;
^~~~~~~~~~~~~
animal_factory.cpp:3:31: error: ‘AnimalFactory* AnimalFactory::animalFactory’ is not a static data member of ‘class AnimalFactory’
AnimalFactory* AnimalFactory::animalFactory = nullptr;
^~~~~~~~~~~~~
animal_factory.cpp: In static member function ‘static AnimalFactory* AnimalFactory::getAnimalFactory()’:
animal_factory.cpp:17:8: error: ‘animalFactory’ was not declared in this scope
if(animalFactory == nullptr)
^~~~~~~~~~~~~
animal_factory.cpp:19:12: error: ‘animalFactory’ was not declared in this scope
return animalFactory;
^~~~~~~~~~~~~
#include "animal_factory.h"
AnimalFactory* AnimalFactory::animalFactory; //If this is not correct way of defining, kindly let me know what's the correct way
AnimalFactory* AnimalFactory::animalFactory = nullptr;
FactoryMap AnimalFactory::factoryMap;//If this is not correct way of defining, kindly let me know what's the correct way
AnimalFactory::AnimalFactory()
{
Register("cat", &Cat::create);
Register("dog", &Dog::create);
}
AnimalFactory::AnimalFactory(const AnimalFactory &) {}
AnimalFactory & AnimalFactory::operator=(const AnimalFactory &) { return *this;}
AnimalFactory* AnimalFactory::getAnimalFactory()
{
if(animalFactory == nullptr)
returnnew AnimalFactory();
return animalFactory;
}
void AnimalFactory::Register(const std::string &s, CreateAnimalFn fPtr)
{
factoryMap[s] = fPtr;
}
Animal* AnimalFactory::createAnimal(const std::string &s, unsignedint p_nLegs)
{
auto it = factoryMap.find(s);
if(it != factoryMap.end())
return it->second(p_nLegs);
returnnullptr;
}