Home > front end >  Call derived class appropriately
Call derived class appropriately

Time:04-23

I have a class order and two derived classes: single_order and repeated_order.

struct order{
string desc;
};
struct single_order : public order{
datetime dt;
};
struct repeated_order : public order{
datetime dt1;
datetime dt2;
};

I have a list<order*> ll that can contain single_order and repeated_order and two methods:

bool is_expired(single_order &el){
   if(today>el.dt){
      //do something
   }
}
bool is_expired(repeated_order &el){
   if(today>el.dt1){
      //do something
   }
   if(today>el.dt2){
      //do something else
   }
}

I would like to iterate over ll and call the most appropriate method in each case. (the parameter of the two functions may also be other than a reference)

How to do that?

CodePudding user response:

You knew to tag polymorphism, but you seem to be struggling with the concept. Here's some code:

#include <iostream>
#include <memory>
#include <vector>

class Base {
 public:
  Base() = default;
  virtual ~Base() = default;
  virtual void do_foo() = 0;
};

class Bar : public Base {
 public:
  Bar() = default;
  void do_foo() override { std::cout << "From Bar\n"; }
};

class Baz : public Base {
 public:
  Baz() = default;
  void do_foo() override { std::cout << "From BAZ\n"; }
};

int main() {
  std::vector<std::unique_ptr<Base>> v;

  v.emplace_back(new Bar());
  v.emplace_back(new Baz());

  for (const auto& i : v) {
    i->do_foo();
  }
}

You can see that in Base, there is a pure virtual function, virtual do_foo() = 0; This means a couple things. Base is a pure virtual class and you cannot declare Base objects, only pointers or references to Base. In order to have a concrete class, or one that you can create objects of, you need to override those pure virtual functions.

You have a function that you want to be able to call on both derived types. This is a perfect example of how polymorphism can make your life easier. You can see that each derived class overrides the pure virtual function and does its own thing, and I am then able to store both derived types in the vector in my main() function, and call the appropriate function on each object.

Output:

❯ ./a.out 
From Bar
From BAZ
  • Related