Jan
Jan

Reputation: 21

Typcasting vector<object> in C++?

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.

Upvotes: 1

Views: 242

Answers (3)

R&#233;mi
R&#233;mi

Reputation: 3745

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.

Upvotes: 3

Charles Salvia
Charles Salvia

Reputation: 53289

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) { ... }

Upvotes: 3

Billy ONeal
Billy ONeal

Reputation: 106540

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....)

Upvotes: 7

Related Questions