huangkaiyi
huangkaiyi

Reputation: 123

Pass two derived class in a vector in function parameter

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

Upvotes: 1

Views: 97

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

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();
}

Upvotes: 1

Related Questions