Reputation: 319
I would like to play with a vector of objects. Let's assume I have a Base
class and two derived classes: Derived_A
and Derived_B
.
class Base{...};
class Derived_A: public Base{};
class Derived_B: public Base{};
In the main()
I create a vector of 10 objects of class Derived_A
e.g.:
std::vector < Derived_A > array;
array.reserve(10);
Now, what I would like to do, is from the elements of this vector, to pick one (or several) and change its type to Derived_B
. At the end, I would have a vector of some elements of class Derived_A
and some of class Derived_B
.
Is that possible? Or would you have a better way to do it?
Upvotes: 0
Views: 82
Reputation: 310980
This
std::vector < Derived_A > array;
array.reserve(10);
does not define a vector of 10 objects. it defines a vector of 0 objects.
As for your question then an object of type Derived_A may not be converted to an object of type Derived_b in general case. The usual approach in this case is to define a vector of pointers to the base class. For example
std::vector<Base *> v;
and add to it pointers to objects of Derived_A and Derived_B. The derived classes should inherite virtual functions of the base class. The destructor also has to be declared as virtual.
Upvotes: 1
Reputation: 1761
You would need several things to be true, I would think:
Base
rather than one of the Derived
s, and even then you couldn't be storing objects but pointers/references.Upvotes: 1
Reputation: 385144
No, that doesn't make any real sense. Derived_A
and Derived_B
are not compatible; only the Base
part of each is.
If you have a std::vector<Base*>
and virtual
member functions, then you can [indirectly] store objects of either type, but don't go casting one to the other.
Incidentally, vectors are not arrays, and std::vector::reserve
does not create elements. It only reserves memory space for them. You probably meant std::vector::resize
.
Upvotes: 3