Christophe J. Ortiz
Christophe J. Ortiz

Reputation: 319

type conversion of some elements of a vector of objects

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

Answers (3)

Vlad from Moscow
Vlad from Moscow

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

tabstop
tabstop

Reputation: 1761

You would need several things to be true, I would think:

  1. It would have to be actually feasible to convert a Derived_A to a Derived_B, and for "sibling" classes that would be pretty unusual.
  2. You would have to be storing using Base rather than one of the Deriveds, and even then you couldn't be storing objects but pointers/references.
  3. The conversion (probably) wouldn't happen in-place, so you may have to remove/reinsert.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

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

Related Questions