Search code examples
c++boostcastingpolymorphismptr-vector

Accessing method of derived class when using ptr_vector


Setup

class Base
{
public:
    Base();
    virtual ~Base();
    int getType();
protected:
    int type;
};

class DerivedA : public Base
{
public:
    DerivedA() { this->type = 1; };
    ~DerivedA();

    int getA() { return 1;};
};

class DerivedB : public Base
{
public:
    DerivedB() { this->type = 2; };
    ~DerivedB();

    int getB() { return 2;};

};

Target

Having a vector containing objects of both derived classes and then be able to access child-specific methods.

Current "solution"

int main()
{
    typedef boost::ptr_vector<Base> BasePtr;
    BasePtr vec;

    // Fill vec with some stuff 
    vec.push_back(new DerivedA());
    vec.push_back(new DerivedB());
    vec.push_back(new DerivedA());
    vec.push_back(new DerivedB());

    typedef BasePtr::iterator BaseIter;

    for ( BaseIter it = vec.begin(); it != vec.end(); it++ ) {

       if (it->getType() == 1) {
          std::cout << it->getA() << '\n';
       } else {
          std::cout << it->getB() << '\n';
       }    

    }

    return 0;
 }

Problem

Obviously "it" is not recognised as either DerivedA or DerivedB, so the child-specific method cant be accessed. Some form of cast is required, so i guess the question is:

How do I properly cast the iterator to the correct derieved class?

Maybe there is a better way to structure this whole scenario?

Edit: Seems i was a bit unclear. The purpose of the methods in the derived classes is fundamentally different. Consider the base class Item that have the derived classes Armor and Weapon.

In this example you can see why, for instance, Weapon have a function getDamage() that maybe returns a float.

This function is not needed for Armor and dosn't even have anything similar.

In this example you can see the vector as an Inventory that can contain any number, and types, of items. Maybe even items that have a stack and some use (Potions maybe)


Solution

  • If you have to cast to derived, then it means you have a broken design.

    But if you really have to then this would do (put it in the for loop) :

    DerivedB * typeB = dynamic_cast< DerivedB * >( &*it );
    if ( typeB != nullptr )
    {
      std::cout << typeB->getB() << '\n';
    } 
    

    A better approach would be to add getB() to the interface, and implement it in DerivedA (it can return some dummy value, or throw if really needed).