In a base class constructor, I would like the instance a derived class. Can I do something like that?
class InterfaceClass // Final user only sees this class
{
enum class TYPE
{
CHILDONE
};
public:
InterfaceClass(TYPE);
virtual void hello_world() = 0;
virtual void print_class();
};
class ChildOne : public InterfaceClass
{
public:
ChildOne() = default;
void hello_world();
private:
};
InterfaceClass::InterfaceClass(TYPE type)
{
if (type == CHILDONE)
this = new ChildOne();
else
throw "NOT HANDLED";
}
void InterfaceClass::hello_world() {
std::cout << "Hello world from InterfaceClass" << std::endl;
}
void InterfaceClass::print_class() {
std::cout << "Not implemented" << std::endl;
}
void ChildOne::hello_world() {
std::cout << "Hello world from ChildOne" << std::endl;
}
// Final user will see only declaration of InterfaceClass
int main()
{
InterfaceClass* ic = new InterfaceClass(InterfaceClass::TYPE::CHILDONE);
ic->hello_world();
}
I would like to build an architecture that behaves like this. But I do not know how to do it properly.