b._.rett
b._.rett

Reputation: 99

Store abstract derived class objects in base class vector

I've learned to store derived class pointers in base class vectors by storing base class pointers:

vector<base*> base_vector;
base_vector.push_back(new derived());
// free memory at the end

But if I have an abstract base class:

class interface {
public:
    virtual interface(){} 
    virtual ~interface(){}
};

From which two more abstract classes are derived.

class abstract_derived_1 : virtual public interface 
{ 
public:
    virtual abstract_derived_1(){} 
    virtual ~abstract_derived_1(){}
};

class abstract_derived_2 : virtual public interface 
{ 
public:
    virtual abstract_derived_2(){} 
    virtual ~abstract_derived_2(){}
};

And several other derived classes from the secondary abstract classes:

class derived_1 : virtual public interface, virtual public abstract_derived_1
{
private:
    double value;
public:
    derived_1(){value=0;}
    derived_1(const double val1, const double val2) { value = val1+val2; }
    ~derived_1(){}
};


class derived_2 : virtual public interface, virtual public abstract_derived_2
{
private:
    string name;
public:
    derived_2(){name="";}
    derived_2(string my_str) { name = my_str; }
};

Is it possible to store all of them in a polymorphic vector? As usual, I did the following:

vector<abstract_derived_1*> abs1;
vector<abstract_derived_2*> abs2;
abs1.push_back(new derived_1(1,2));
abs2.push_back(new derived_2("polymorphism"));

But how do I store the two polymorphic vectors in a base class vector?

vector</* What should I put in here? */> interface_vector;

Upvotes: 0

Views: 339

Answers (2)

tangoal
tangoal

Reputation: 769

There is no problem to just push_back new instances of derived_1 and derived_2 to a generic vector vector<interface*>, because they have the interface class as ancestor.

By the way: you don't need the derived_1 class and derived_2 class to inherit from interface again. This is a uncommon and I am quite sure that this may lead to other problems.

Upvotes: 1

wes
wes

Reputation: 1

vector<interface*> interface_vector;
// Loop through abs1 with an index of i
interface_vector.push_back(dynamic_cast<interface*>(abs1[i]));
// Loop through abs2 with an index of i
interface_vector.push_back(dynamic_cast<interface*>(abs2[i]));

Just add the loop above. The main point is that you're able to cast to interface* which is what your vector<interface*> expects.

Upvotes: 0

Related Questions