0

I have an array of base classes, the items thereof contain a child class. The problem is that when I try to access the child class in the array I get the error no operator "[]" matches these operands when I try to do:

shared_ptr<P>& tmpP= (*arrayOfC)[(int)x][(int)y];

I am trying to access the child class. If I do:

arrayOfC[(int)x][(int)y]

then i can access the base class which is not what I am after. I have tried using dynamic_cast to no avail.

The array is

shared_ptr<C> arrayOfC[800][600];

This is declared in another header file and does use forward declaration as well. This is how its being saved:

shared_ptr<P> childClassP= make_shared<P>(z, x, y);
arrayOfC[(int)x][(int)y] = std::move(childClassP);
user438383
  • 5,716
  • 8
  • 28
  • 43
David Benz
  • 49
  • 6

1 Answers1

1

You need to use std::dynamic_pointer_cast, plus, you also need to have at the very least, a virtual destructor in the base class in order to generate vtables to make the classes polymorphically related.

#include <memory>

struct C {
    virtual ~C() {}
};

struct P : public C {

};

std::shared_ptr<C> arrayOfC[8][6];

int main() {
    auto derived_ptr = std::make_shared<P>();
    int x {2};
    int y {2};
    arrayOfC[x][y] = std::move(derived_ptr);

    // does not compile: std::shared_ptr<P> view = arrayOfC[x][y];

    std::shared_ptr<P> view = std::dynamic_pointer_cast<P>(arrayOfC[x][y]);

    return 0;
}

See http://www.cplusplus.com/reference/memory/dynamic_pointer_cast/

Demo: https://godbolt.org/z/qn9oq4zfb

Den-Jason
  • 2,395
  • 1
  • 22
  • 17