Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call derived class appropriately

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to do that?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading