After searching for hours, I end up here. I have a Container class with a pointer to Base class as member variable. This should either refer to Spec1 or another inherited classes of Base, which I omitted here. The type should be determined by the argument in constructor (e.g. string, enum, int, etc.).
I read much about dynamic memory allocation and why it should be avoided whenever possible. Is it possible to avoid here? Isnt any usual object destroyed after the constructor? Or is the design idea completely wrong? I come from Java :( Thanks in advance.
class Base{
public:
virtual ~Base(){}; // required?
virtual void doSomething() = 0;
};
class Spec1 : public Base {
public:
Spec1(){};
Spec1(int i){
// whatever
}
void doSomething(){
std::printf("hello world");
}
};
class Container{
public:
Container(String type_message){
if (type_message.compare("We need Spec1")){
m_type = new Spec1(1);
} // add more ifs for other types (Spec2, Spec3 etc.)
}
void doSomethingWithSpec(){
m_type->doSomething();
}
private:
Base* m_type;
};
int main (int argc, char **argv){
Container a ("We need Spec1");
a.doSomething();
}