user2165489
user2165489

Reputation: 1

C++ array of inheritance

The question is about C++. I have 3 classes: the first, named MovieMaker, is abstract, the second, named Actor, is derived from the first one and the third, named 'Director' derives from Actor. I want to create an array that can hold instances of both Actor and Director. How can I do that?

Upvotes: 0

Views: 166

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

Create an array of std::shared_ptr<MovieMaker>, or unique_ptr. In C++, it is usually a good idea to create a std::vector instead of a raw array: so std::vector<std::shared_ptr<MovieMaker>> vec, which you populate like this:

#include <vector>
#include <memory>

// later:
std::vector<std::shared_ptr<MovieMaker>> vec;
vec.push_back( std::make_shared<Actor>() );
vec.push_back( std::make_shared<Director>() );
vec.push_back( std::make_shared<Actor>() );

or, in C++11:

#include <vector>
#include <memory>

// later:
std::vector<std::shared_ptr<MovieMaker>> vec = {
  std::make_shared<Actor>(),
  std::make_shared<Director>(),
  std::make_shared<Actor>(),
};

If you are willing to use boost, a 3rd party library, there are a few other options.

Alternatively, create an array of boost::variant<Actor,Director>, which ignores the class hierarchy and simply stores a type-safe union like construct. boost::variant is a bit trick to use.

As another alternative, boost::any can store anything, and you can query it if what it has is what you want.

Upvotes: 3

WeaselFox
WeaselFox

Reputation: 7380

create an array of MovieMaker pointers. it can hold pointers to derived classes. This technique is called polymorphism - here is a nice tutorial:

http://www.cplusplus.com/doc/tutorial/polymorphism/

Upvotes: 3

Related Questions