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;
virtual
and how do you manage to assignderived_2 *
toabstract_derived_1 *
? – Killzone Kidvirtual
but also= 0
as well, eg:virtual void doSomething() = 0;
. And constructors can't bevirtual
, but destructors can (and should be, in a base class) – Remy Lebeau