I'm trying to create a class Animal, with some subclasses that have a interface method newObject() return new instance of self:
Animal.h
class Animal{
public:
virtual Animal* newObject()=0;
};
and I am trying to implement registry pattern, with a class AnimalRegister, which stores mapping between class name and an instance of the class:
AnimalRegister.h
#include <map>
class Animal;
class AnimalRegister{
public:
static void* add(const char* name,Animal* a);
static Animal* get(const char* name);
protected:
static std::map<const char*,Animal*> m;
};
AnimalRegister.cpp
#include "AnimalRegister.h"
#include <stdio.h>
std::map<const char*,Animal*> AnimalRegister::m;
void* AnimalRegister::add(const char* name,Animal* a){
m[name]=a;
printf("%s registered\n",name);
return NULL;
}
Animal* AnimalRegister::get(const char* name){
return m[name];
}
when I add a subclass Cat:
Cat.h
#include "Animal.h"
class Cat : public Animal{
public:
virtual Animal* newObject();
protected:
static void* Cat_;
};
Cat.cpp
#include "Cat.h"
#include <stdio.h>
#include "AnimalRegister.h"
void* Cat::Cat_=AnimalRegister::add("Cat",new Cat());
Animal* Cat::newObject(){
printf("Cat::newObject");
return new Cat();
}
the line
void* Cat::Cat_=AnimalRegister::add("Cat",new Cat());
maps the string "Cat" to instance of Cat, so that later I can create a new Cat by name:
Animal* a=AnimalRegister::get("Cat")->newObject();
instead of
if(string(name)=="Cat"){
return new Cat();
}
that violates open closed principle when add a new subclass.
but when I try to test the code above:
#include "Cat.h"
#include "AnimalRegister.h"
int main(){
printf("#1");
Animal* a1=AnimalRegister::get("Cat");
printf("#2");
Animal* a2=a1->newObject();
printf("#3");
};
the output is only:
Segmentation fault: 11
and seems never reaches the main,what is the reason?