1

I have these classes:

  • a Base class
  • a Child class which needs more space than Base.

Something like this:

class Base{
};


class Child : Base{
   int something;
};

And I define a std::vector containing Base class instances.

For example: I want to reserve space instead of using push_back() for every Child object. Is there any solution to resize the vector upon the class Child?

radical7
  • 8,957
  • 3
  • 24
  • 33
Saeed
  • 33
  • 1
  • 6
  • You can't do so! Use pointers (preferably smart pointers) to store references to those objects in your vector. – πάντα ῥεῖ Dec 30 '13 at 15:37
  • The problem is that I want to get a vector from user in C++03. The vector could contain many objects. Thereafter I need efficiency, polymorphism and vectors. It seems completely wrong idea – Saeed Dec 30 '13 at 16:26

1 Answers1

1

It's either a vector of Base or a vector of Child. It can't be both. If you declare a std::vector<Base> and attempt to put Childs into it, you will slice them and only get the Base part of those Childs.

If you want polymorphism, you'll have to have a vector of Base*. Then the space used for each element of the vector is just the size of a pointer - that pointer can point at a Base or a Child.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Any idea in C++03 rather than pointers? I want to deal with object deletion inside of code. – Saeed Dec 30 '13 at 16:29
  • @Saeed Well polymorphism works with pointers or references, so you have to use one of them. You could use [`boost::reference_wrapper`](http://www.boost.org/doc/libs/1_55_0/doc/html/boost/reference_wrapper.html) or a smart pointer from Boost. – Joseph Mansfield Dec 30 '13 at 16:31