0

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Amaterastis
  • 477
  • 3
  • 12
  • *"Without Super class as soon as I would type dynamic_cast, compilation phase will abort with an error (Base is not a polymorphic class)."* -- it should work without `Super` as long as you have a virtual function in `Base` (e.g. get rid of `override` and add `virtual` to the existing definition of `v()`). – JaMiT Nov 26 '22 at 23:37
  • *"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?"* -- A virtual function does not prevent construction of `Base` objects. A **pure virtual** function would, but not a "normal" virtual function. – JaMiT Nov 26 '22 at 23:39
  • Your code fails because you are [**slicing** the objects](https://stackoverflow.com/questions/274626/what-is-object-slicing) in the `vector`. Polymorphism doesn't work unless you use pointers/references to objects, so use `Base*` instead in both the `vector` and `dynamic_cast` and then your code will work as you want: [demo](https://ideone.com/RvSq75) – Remy Lebeau Nov 27 '22 at 01:26

0 Answers0