Invoke unique functions of derived classes from a vector of pointers to base class objects

#include <iostream>
#include <vector>

using namespace std;

class Base
{
public:
    void speak() { cout << "Hello!"; }
};

class Derived1 : public Base
{
public:
    void func1() { cout << "I'm a function!"; }
};

class Derived2 : public Base
{
public:
    void func2() { cout << "I'm also a function!"; }
};

int main()
{
    vector<Base*> v = { new Derived1(), new Derived2(), new Derived1(), new Derived2() //, ...
    };
    // For each Derived1 object invoke func1() and for each Derived2 object invoke func2()
}

Base is not polymorphic (no virtual function). From these conditions how can I be able to invoke func1 for each Derived1 object and func2 for each Derived2 object in v?

Upvotes: 0

Views: 131

Answers (2)

Barry
Barry

Reputation: 303216

As-is, it's impossible. You can't do dynamic_cast, no member that indicates one type or the other. There's absolutely no way to distinguish given a Base* whether it's a Derived1* or a Derived2*.

You would have to do one of:

  1. Add a virtual void func() = 0; that the two different classes would override.

  2. Add a member variable of type std::function<void()> that would be set in the Base constructor differently by the two Derived classes.

  3. Add a member variable that's an enum to indicate which Derived it is, so that you could do a switch externally to do a safe static_cast.

  4. Add a virtual ~Base() so that that instead of a switch, you would do dynamic_casts.

  5. Not actually have either Derived1 or Derived2 inherit from Base, but instead have a variant<Derived1, Derived2>.

  6. ???

  7. Profit.

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"Base is not polymorphic (no virtual function)."

You still can do a static_cast<Derived1>(v[0]) / static_cast<Derived2>(v[1]), a.s.o, as long you're sure what you'll get at a particular index.

Upvotes: 1

Related Questions