Topic: More Portability of Casting
Author: JIMI@RALVM5.VNET.IBM.COM (Jim Meyers)
Date: Thu, 14 Jan 93 15:36:43 EST Raw View
I guess my first post was too confusing. I'll try to be more direct:
Assume we have the following data types:
struct Base {...}; // Never contains methods - only data members
class Derived : public Base {
...
virtual int bar(); // Derived class may or may not have virtual methods
...
};
Now, we want to cast a Derived* to a Base* for the purposes of passing
a struct Base* to a "C" API e.g.:
main()
{
Derived d;
int rc = foo( (Base*)&d );
}
1. Is this portable?
2. Is a (Base)Derived always bitwise equivalent to a struct Base?
3. Is a (Base*)&Derived always equivalent to a struct Base*?
4. Does the language definition allow compiler vendors to associate a
vtbl* with the Base part of d (even though Base has no virtual
methods)?
-------------------------------------------------------------------------
Jim Meyers | Voice: 919-543-5999
IBM Networking Systems | Fax: 919-543-1286
LAN Systems Workstation Technology |
Research Triangle Park, NC 27709 | Internet: jimi@ralvm5.vnet.ibm.com
=======================================================================
Author: dwr@cci632.cci.com (Donald W. Rouse II)
Date: 15 Jan 93 18:00:06 GMT Raw View
In article <19930114.130310.646@almaden.ibm.com> JIMI@RALVM5.VNET.IBM.COM (Jim Meyers) writes:
>I guess my first post was too confusing. I'll try to be more direct:
>
>Assume we have the following data types:
>
> struct Base {...}; // Never contains methods - only data members
>
> class Derived : public Base {
> ...
> virtual int bar(); // Derived class may or may not have virtual methods
> ...
> };
>
>Now, we want to cast a Derived* to a Base* for the purposes of passing
>a struct Base* to a "C" API e.g.:
>
> main()
> {
> Derived d;
>
> int rc = foo( (Base*)&d );
> }
>
Wouldn't this work better?
extern "C" int foo (Base&); // In C, declare int foo (Base*);
...
int rc = foo (d);
I don't know if this is strictly legal, though.
(Do C++ refs always translate to C pointers?)
If not, you could use
Base* baseof(Base& b) { return &b; }
extern "C" int foo (Base*);
main()
{
Derived d;
int rc = foo( baseof (d) ); // d ref turns into b ref; ->b returned
}