rocd
rocd

Reputation: 1

Best way of returning a derived class pointer from a class working on a set of base class pointers

I have an abstract Base class and multiple derived classes from that Base class, representing different kinds of objects all having the same property of weight.

The purpose of the Selector class is to select an object from the passed collection of (homogeneous) objects, based on some algorithm that will use the weight (via getWeight API) as the input. The number of derived classes from Base will continue to increase in the future, and the Selector algorithm itself can also evolve, but the input parameters will remain unchanged.

I am sending the derived objects down to the Selector class as pointers to the Base class. Since this is upcasting, it should be a trivial operation. The caller to Selector knows the type of the object being passed.

Can I get back the result without needing to use a dynamic_cast? A static_cast can potentially be used as the caller always knows the object type. I am trying to see if there is a design flaw as I need an explicit cast when fetching the result from the class. I was wondering if there is a design pattern that can help me avoid an explicit cast.

I am trying to avoid using templates, as it has led to build-time challenges in the past. However, I am open to using them if that is a better design for this kind of usage.

class Base {
  virtual int getWeight() = 0;
};

class DerivedA : public Base {
  public:
  int getWeight() { return _weight; }
  
  private:
  int _weight = 0;
  string _name;
}; 

class DerivedB : public Base {
  public:
  int getWeight() { return _weight; }
  
  private:
  int _weight = 0;
  float _multiplier = 1;
}; 


// Calls the getWeight function of each object and selects on of the object based on some algorithm (e.g. max)
class Selector {
  public:
  Selector(vector<Base*>);
  Base* getResult();
  
};

void CallingFunctionA(vector<DerivedA *> v) {
  vector basePointers = getBasePointerVec(v);
  Selector s(basePointers);
  // Can a dynamic_cast be avoided?
  DerivedA* result = dynamic_cast<DerivedA *> s->getResult();

}
void CallingFunctionB(vector<DerivedB *> v) {
  vector basePointers = getBasePointerVec(v);
  Selector s(basePointers);
  // Can a dynamic_cast be avoided?
  DerivedB* result = dynamic_cast<DerivedB *> s->getResult();

}

Upvotes: 0

Views: 56

Answers (0)

Related Questions