Reputation: 66
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?
Upvotes: 0
Views: 446
Reputation: 126243
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
Upvotes: 1