user3496846
user3496846

Reputation: 1665

Conversion to a vector of unique base class pointers

EDIT

As requested, I am providing an example:

#include <iostream>
#include <vector>
#include <memory>

using namespace std;

class Animal
{
    public:
        virtual void printName() = 0;
};

class Dog: public Animal
{
    public:
        virtual void printName() { cout << "Dog" << endl; }
};

class Cat: public Animal
{
    public:
        virtual void printName() { cout << "Cat" << endl; }
};

int main()
{
    vector<vector<unique_ptr<Animal>> *> groups_of_animals;

    vector<unique_ptr<Dog>> dogs;
    vector<unique_ptr<Cat>> cats;

    dogs.push_back(unique_ptr<Dog>(new Dog));
    dogs.push_back(unique_ptr<Dog>(new Dog));
    cats.push_back(unique_ptr<Cat>(new Cat));

    groups_of_animals.push_back(reinterpret_cast<vector<unique_ptr<Animal>> *>(&dogs));
    groups_of_animals.push_back(reinterpret_cast<vector<unique_ptr<Animal>> *>(&cats));

    for(auto &group: groups_of_animals)
        for(auto &animal: *group)
            (animal) -> printName();

    return 0;
}

Output: Dog Dog Cat

Is using reinterpret cast safe and justified here? Static cast does not work.

PS I found this topic: I want a vector of derived class pointers as base class pointers but in my situation I am using unique_ptr and want I do not want to update the everyone vector as soon as I update some child vector. I just want to have pointers to those child vectors.

Upvotes: 1

Views: 530

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

You cannot do this for a simple reason that neither reinterpret_cast, nor static_cast nor dynamic_cast works this way.

When you have a:

class Superclass {};

and a

class Subclass : public Superclass {};

You can, under certain circumstances, use one of the appropriate casts to cast an instance of one to another.

But you cannot cast a std::vector of one to a std::vector of the other, as it seems you're attempting to do here. Neither of the two vector classes are a direct superclass or a subclass of the other vector class. std::vector is a template. Each instance of a template is a unique class of its own, that's not related to any other instance of the template (unless explicitly declared, as such, using specialization, etc...)

Upvotes: 3

Related Questions