Adam
Adam

Reputation: 177

Creating a container to store multiple types

I have a class which contains pure virtual functions. I am using this class to make sure I do not forget to implement some methods in derived classes.

I have a collection of derived classes like

class B : public A
class C : public A
class D : public A 
etc

How can I create a container that can hold all of these derived classes (B,C,D)? I would prefer to use a standard container such as vector. I tried creating a vector of the base class but this results in the derived classes being converted if they are pushed onto the vector leading to a compilation error of invalid new-expression of abstract class type.

My base class:

class A
{
public:
    A();
    virtual ~A();

    virtual double GetVolume() = 0;
};

Example derived class:

class B : public A
{
public:
    B(){};
    virtual ~B(){};

    double GetVolume(){};
};

Upvotes: 2

Views: 1118

Answers (1)

Nir Friedman
Nir Friedman

Reputation: 17704

You need to create a container of pointer-to-base. A container of base objects causes conversion from derived to base, which is called slicing. When you have a pointer-to-base however, the object can still have a different type (a derived one) than the base class, this is called the dynamic type of the object (as opposed to static type).

In modern C++ it's best to use smart pointers for this:

std::vector<std::unique_ptr<A>> x;
x.push_back(std::make_unique<B>());
x.push_back(std::make_unique<C>());
x.push_back(std::make_unique<D>());

for (auto& e : x) {
    e->GetVolume();
}

Upvotes: 5

Related Questions