Reputation: 22731
I don't understand why this inheritance doesn't work. I have the following setup:
struct Shape{}
struct Stain : Shape {}
Now, why can't I do the following:
vector<Shape> shapes;
Stain stain();
shapes.push_back(stain);
I would this expect this to be working since Stain
is a subclass of Shape
, so I should be able to put a Stain
into a vector<Shape>
? Or is this even conceptually wrong and what I am trying to do is indeed not possible?
Upvotes: 2
Views: 289
Reputation: 39370
For polymorphism in C++ you need reference semantics. The easiest way to achieve that would be std::vector<std::unique_ptr<Shape>>
.
Alternatively, if you want to be able to copy your shapes, look at value_ptr
concept. A lot of implementations also allow COW (Copy-on-Write). Essentially for nearly all purposes it works just like a value, e.g. a copy of it makes a copy of the value it holds and allocates it.
The obvious change is that you can't treat your vector as a POD memory block anymore.
Upvotes: 10