Question

I am new to c++ and i have a question.

Lets say we have a base class Base and two derived classes, Derived1 and Derived2. f.e. Derived1 has a constructor taking a integer and Derived2 a constructor taking a boolean.

Is it possible to determine at run time (or at compile time) which of those two subclasses to create and assign it to the Base class.

Something like this: Base b = ???(value), where value is of type integer or boolean.

Thanks in advance!

Was it helpful?

Solution

You probably want Factory Design Pattern.

OTHER TIPS

Write two overloads of a function called createMyBlaBla. One accepting int, and the other accepting bool. Everyone returns the desired derived class type. e.g.:

Base* create(int n)
{
    return new Derived1(n);
}
Base* create(bool b)
{
    return new Derived2(b);
}
....
Base* b1 = create(10);    // Derived1
Base* b2 = create(false); // Derived2

People call this the factory pattern.

I don't really think this is possible the way you want it to be, polymorphism in C++ just doesn't work like this.

If I understood well, you want a variable declared as Base decides, depending on the parameter type, whether it is going to be Derived1 or Derived2, all without using the Factory pattern.

The reason why this is not possible is that, the Base class is not really aware of the existence of its Derived classes nor you can declare a stack variable and make it "behave" as a derived class. However, I can suggest a work-around but then again, this doesn't satisfy all the expectations of the real class hierarchy you want (if you really want it that way_:

class Facade{

public:
    Facade(int foo) : b(new Derived1(foo)){}

    Facade(bool foo) : b(new Derived2(foo)){}

    Base Value()
    {
        return *b;
    }

private:
    Base* b;

};

And then you can do something like:

Facade foo(10);
Facade bar(true);

int x = (reinterpret_cast<Derived1*>(foo.Value())) -> val;
bool y = (reinterpret_cast<Derived2*>(bar.Value())) -> val;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top