LargeLizard
LargeLizard

Reputation: 66

Use derived class methods with unique_ptr to base class

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

Answers (1)

Chris Dodd
Chris Dodd

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

Related Questions