I would like to be able to initialize a class member in one of N ways (in this examples N=2) based on a condition that is recieved via the class constructor as in the code that follows, but the MainObject's initialization seems to be only local to the (container) class' constructor. I wonder what are the best-practices for this particular pattern.
// in ContainerObject.hpp
class ContainerObject {
public:
MainClass MainObject;
ContainerObject(int type);
}
// in ContainerObject.cpp
ContainerObject::ContainerObject(int type);{
if (type == 0){
MainObject("something", 1, 2);
} else if (type == 1){
MainObject(4, "another thing", "yet another thing");
}
}
I have so-far thought about
- putting the main object in the heap
- defining N class constructors and call the appropiate one recursively inside the "main"/"first" class constructor.
please note that the "0" and "1" initialization is only an example and it could be drastically different.
EDIT1: added ";" required for compiling EDIT2: Changed the original
//...
if (type == 0){
MainObject(0);
} else if (type == 1){
MainObject(1);
}
//...
for the current one
//...
if (type == 0){
MainObject("something", 1, 2);
} else if (type == 1){
MainObject(4, "another thing", "yet another thing");
}
//...
as it was called a duplicate by being misinterpreted for a case that could be solved by adding the following.
//...
ContainerObject(int type): MainObject(type);
//...