mardi 1 août 2017

How to call derived class function (based on its type) from a container which contain pointer of base class?

I inherit from Base class to create two different Derived class ( Derived1 and Derived2), Then I place them into a vector. Lets say I want to call the function of Derived class based on the type of class.

eg: if holder[1] stored Derived1 then I want to call GetZ() else if holder[1] stored Derived2 then I want to GetFlag().

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

class Base {
 public:
  Base(int x, int y) : x_(x), y_(y) {}

  int GetX() { return x_; }
  int GetY() { return y_; }

 private:
  int x_;
  int y_;
};

class Derived1 : public Base {
 public:
  Derived1(int x, int y, int z) : Base(x, y), z_(z) {}

  int GetZ() { return z_; }

 private:
  int z_;
};

class Derived2 : public Base {
 public:
  Derived2(int x, int y, bool flag) : Base(x, y), flag_(flag) {}

  bool GetFlag() { return flag_; }

 private:
  bool flag_;
};

std::vector<std::shared_ptr<Base>> holder;
void print();
int main() {
  holder.push_back(std::make_shared<Derived1>(3, 4, 5));
  holder.push_back(std::make_shared<Derived2>(6, 7, true));

  print();
}

void print(){

  for(auto& it : holder){
    // call this if "it" is Derived2
    // else call it->GetX()
    // currently this gives compilation error 
    // because of object slicing
    std::cout << it->GetFlag() << std::endl;
  }

}

Aucun commentaire:

Enregistrer un commentaire