The reason for this is because the casted pointer may not point to the same address. For example:
1 2 3 4
|
DerivedObject* foo = &someobject;
Object* bar = foo;
if(bar == foo) // <- this is not guaranteed to be true!
|
since the casted pointer is not guaranteed to be equal to the original pointer, a container holding the original pointers being reinterpretted as casted pointers could result in all the pointers being bad/corrupt. |
Well, I am not totally sure about the specification when comparing pointers, but it should be fine to cast a single DerivedObject to an Object. A DerivedObject i
s an Object. The pointers should be equal. It just may be undefined to compare them, since they do not point into an array.
You can not safely use such cast when accessing a container though. In you have a pointer into a container of DerivedObjects, and you cast it to a pointer to Object, any pointer arithmetic with it as an Object pointer will be incorrect since Object and DerivedObject are probably not the same size. Any arithmetic will add or subtract the wrong byte offset into the array. This probably wouldn't be the wrong element, it would actually point into part of an element as if it was the start of a different element; very bad.
That is not what the original poster is doing here. You don't have a container of Objects or DerivedObjects, you have a container of pointers to Objects, and a container of pointers to DerivedObjects. Pointers should be the same size, so a reinterpret_cast may work. It can be implementation defined though, and is not recommended.
The proper way to do this is to not use a container of DerivedObject* in the first place. Your function wants a container of Object pointers, so when you create your DerivedObjects and populate the vector, just use a vector of Object*, and cast the DerivedObject* to Object* when you insert them. It is common to have containers of pointers to a base class, but actually put pointers of derived classes into it, and use virtual function calls to get the desired behavior for each object.
So, do you have a good reason to actually need a vector of DerivedObject pointers?
In the unlikely event that you actually do, then you could possibly implement use_objects() as a template function, but that would require careful implementation; it is easy to make it take any type of pointer, but it is probably only meant to work with classes descended from Object.