0

I have a Base class and a multiple Derived classes (with their own .h and .cpp files) looking something like this

class Base {
    // Base stuff
}

class Derived : public Base {
   public:
   derivedOnlyFunc();
}

class SecondDerived : public Base {
   public:
   derivedOnlyFunc2();
}

In my main file I have a vector of unique pointers to base that point to derived objects. However, I want to call on derivedOnlyFunc().

vector <unique_ptr<Base>> baseVector = {new Derived(), new Derived()}

for (auto object : baseVector)
    // Want to use object.derivedOnlyFunc() here

I can't change baseVector to be a vector of unique_ptr Derived as it will contain more than one derived class. How can I use the derived class's functions?

1
  • 6
    dynamic_cast is your friend. It helps you convert a Base* to a Derived* or a Base& to a Dervied&. Commented May 24, 2020 at 18:14

1 Answer 1

1

Dynamic cast is what generally what you want for this kind of pattern

if (auto der = dynamic_cast<Derived *>(object.get()))
    der->derivedOnlyFunc();
else
    // is not a Derived
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.