The code I am working with is for learning purpose only.
I have a vector with Base defined. I want to store both Derived1 and Derived2 objects inside. Single element of a vector is passed to a function. Inside a function I want to call a different prompt depending on if the passed object is actually of type Derived1 or Derived2.
class Super { virtual void v(void) = 0; };
class Base : public Super { inline void v(void) override {} };
class Derived1 : public Base {};
class Derived2 : public Base {};
std::vector<Base> objects;
Derived1 d1;
Derived2 d2;
objects.push_back(d1);
objects.push_back(d2);
void func(Base &b)
{
try
{
(void)dynamic_cast<Derived1 &>(b);
std::cout << "Are you Derived1?" << std::endl;
}
catch (std::bad_cast)
{
try
{
(void)dynamic_cast<Derived2 &>(b);
std::cout << "Are you Derived2?" << std::endl;
}
catch (std::bad_cast)
{
std::cout << "Object type cannot be deduced." << std::endl;
}
}
}
func(objects[0]);
func(objects[1]);
My code always terminates with:
Object type cannot be deduced.
Without Super class as soon as I would type dynamic_cast, compilation phase will abort with an error (Base is not a polymorphic class).
Because Base actually implements virtual method from Super, compilation phase passes, but dynamic_casts between Base and Derived1/2 will always terminate with std::bad_cast because there are no virtual methods that Derived1/2 implement.
How to get around this behaviour without adding virtual function to Base, since I want to be able to instantialise object of Base class as well?