1

I have my Base class and two derived class

class Base{
}
class Derived_1 : public Base{
}
class Derived_2 : public Base{
}

My problem is I have a vector composed of Base element which only have Derived_1/2 element and I would like to pass it in a function like this :

Void function_a( vector<Base> v){
   for(auto e : v)
     function_b(e);
}
void function_b(vector<Derived_1> v){}
void function_b(vector<Derived_2> v){}

Of course this code above won't work because function_b is waiting for a Derived_1/2 but I passed a Base element. Derived_1/2 class have common member that's why I made Base class.

I dont really understand about template or virtual class but I saw that we cannot instantiate it. Tried with boost::any and boost::variant but my project ask me to not add those library. Stackoverflow_question

huangkaiyi
  • 73
  • 2
  • 9
  • 3
    when you store instances of `Derived_1` or `Derived_2` in a vector of `Base` elements there is object slicing. Polymorhpism requires pointers or references (and a virtual destructor) – 463035818_is_not_an_ai Jun 20 '22 at 08:34
  • what exactly is the question? You need to fix the issue with slicing first. Then you can consider to change the functions to take vectors of `std::unique_ptr`. – 463035818_is_not_an_ai Jun 20 '22 at 08:35
  • btw the vector is almost irrelevant for the problem in the posted code. You'd have the same issues without the vector but only a single instance – 463035818_is_not_an_ai Jun 20 '22 at 08:36

1 Answers1

1

You cannot store instances of derived classes in a vector of base elements. For details I refer you to What is object slicing?. You need references or pointers for polymorphism.

Moreoever, in your code, e in the loop is a single element not a vector.

It seems you want to call either of the method depending on the dynamic type of the elements. Thats what virtual methods are for:

#include <vector>
#include <memory>

struct Base{
    virtual ~Base() {}
    virtual void function() = 0;
};

struct Derived_1 : public Base{
    void function() override {}
};

struct Derived_2 : public Base{
    void function() override {}
};



void function_a( std::vector<std::unique_ptr<Base>> v){
   for(auto& e : v)
     e->function();
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185