Rob said:
Code:
(I am not the one who defined these classes)[/QUOTE]
[QUOTE]
class _jobject {};
class _jarray : public _jobject {};[/QUOTE]
[QUOTE]
typedef _jobject* jobject;
typedef _jarray jarray;[/QUOTE]
[QUOTE]
int main()
{
jobject * a;
jarray b;
a = dynamic_cast<jobject*> (&b);
....
}
This doesn't work and the problem is the only type names I'm
guaranteed to have are jobject and jarray. The original _jobject is
how it's defined here but I'm not guaranteed it''ll always be that way
so I have to work with jobject/jarray.
How would I cast between jobject and jarray?
According to the declarations you have given jarray is a synonym for
_jarray which is derived from _jobject, but jobject is synonym for a
POINTER to a _jobject. &b returns a pointer to the instance of _jarray,
which can be converted without a cast, because it is just working up the
class hierarchy, to a pointer to _jobject, which is synonymous with
jobject, not with pointer to jobject. I do not know your objective, but
the following should compile:
int main()
{
jobject a;
jarray b;
a = &b;
}
dynamic_cast is used for moving DOWN the class hierarchy, not up. So if
you have a pointer to _jobject that you have reason to believe is
actually a pointer to _jarray you can:
_jobject * p;
_jarray * q;
// no cast required because an instance of _jarray
// is guaranteed to be an instance of _jobject
p = q;
if (Ihavereasontobelievethat_p_pointstoa_jarray) {
// dynamic_cast required so that the type of
// the _jobject can be verified at run time
q = dynamic_cast<_jarray *>(p);
}
As I see it the problem you are facing is that the name of the typedef
jobject is confusing because it does not warn the programmer that it is
a pointer to a class, not a class itself. If the architect had really
intended to use the jobject and jarray definitions to hide the internal
implementation then they should have been defined explicitly as classes,
not as typedefs.
In any event C++ pointers are extremely dangerous and should be avoided
as much as possible. They are a carryover artifact from C. Their use
exposes you to risks because the compiler cannot catch most misuses.
For example the compiler will permit you to use an instance of jobject
as an array! That is because C permits you to use any pointer as an
array. In your fragment of code what would happen if you coded:
a[3] = b; // !?