views:

80

answers:

3

I have two classes, obstacle and boid, boid inherits from obstacle.

Now I want to write some functions that can work with objects of both classes, so that passing vector<boid> does work as well as vector<obstacle>.

When I typecast like this and try to access the size of the vector I get a number of 1840700394 instead of 60:

vector<boid>* boids; ....
cout << ((vector<obstacle>*)boids)->size() << endl;

I also tryed "reinterpret_cast" but same problem.

+2  A: 

You can't cast a vector to a different type of vector like that. If you need a generic function that works with both types of objects, you can use a function template.

template <typename T>
void func(const std::vector<T>& vec)
{
  ....
}

This function will accept a vector containing any type of object.

Also, see Roger Pate's comment below. You can let the function accept any type of container (or any object that implements the appropriate semantics) by just saying:

template <typename T>
void func(const T& container) { ... }
Charles Salvia
Better yet, make the entire container a template parameter.
Roger Pate
Or pass a range instead of a container?
eq-
@eq-: Sometimes you really need the container; e.g. to call erase or other methods.
Roger Pate
Without reading up all about "templates", i can imagine it is not possible to access members of the objects when using templates?
Jan
You'd imagine wrong. Templates are all-mighty :)
eq-
@Jan: It is possible to access members. In a nutshell, templates are just code generation performed by the compiler for you, so `template<class T> void f(T x) {}` gives you `void f(int x)`, `void f(char x)`, `void f(std::string x)`, ad infinitum.
Roger Pate
+7  A: 

C++ templates are not like C# and Java generics. A template instantiation is a complete class, and is not related to other template instantiations in any way whatsoever. One cannot cast between them.

(Side Note: If you were using static_cast instead it would have caught this for you....)

Billy ONeal
+1 for mentioning static cast not hiding the problem
awoodland
+3  A: 

A simple way to solve this kind of problem is to use a std::vector<obstacle *>. Then you can populate your vector with pointers to any object that inherits from obstacle.

Rémi