0

My situation looks something like this:

class Parent;

class Child1 : public Parent;
class Child2 : public Parent;

class ChildOfChild1 : public Child1;


std::vector<std::vector<Parent>> matrix;

I want to be able to contain all the classes within this one matrix but I am not sure of the best way to do it.

Right now if left as it is every Child I add to the matrix just gets converted into a Parent with all the methods and variables not contained in the Parent removed.

I know something like this should be possible in Java which is also strictly typed so I thought I might ask if it is also possible in C++.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
veqa
  • 57
  • 9
  • You get what you want in Java because Java defaults to reference semantics when dealing with class instances. C++ defaults to value semantics. Instead of storing references to a `Parent` or `Parent`-derived value, C++ will store a `Parent` directly unless you explicitly ask for a reference. – user4581301 Aug 05 '21 at 21:01

1 Answers1

2

I think it is a duplicate of this question

The thing you want to use is called Object Slicing Try this:

std::vector<std::vector<Parent*>> matrix
Adam Kuzański
  • 509
  • 4
  • 12