简体   繁体   中英

Typecasting Member Variable Pointer to Object Pointer

I want to know if typecasting a member variable to object pointer is okay to do in C++?

I have a class as follows -

class Foo
{
private:
    int x;
    int y;
    int z;

public
    void func1(...);
    void func2(...);
    void func3(...);
}

In addition I have a 3rd party code, which has a callback as -

void callbackFunction (int *xPointer)
{
     // This is what I want to do
     Foo * fooPtr = (Foo*)xPointer;
     if(fooPtr->y == fooPtr->z)
     {
          //... do something
     }
}

In this code, the xPointer variable points to int x of my class object. Now, I want to know can I somehow typecast xPointer to Foo * . In C, I typecasted the pointer to struct pointer to access other member, without any problem.

Is there any danger involving such typecast in case of C++?

If it is a problem, then how can I get pointer to object using the pointer to its member variable?

Thank You

To be able to work directly with class pointers to obtain pointers to their members you must make sure that the class is a POD type. Otherwise there could be hidden members (like a vtable ) or paddings that would break any effort.

To know it you should try with std::is_pod<Foo> which is a convenience trait class that will tell you if the class has a standard layout.

In any case it sounds like you should avoid this approach, since it seems inherently unsafe. Why can't you just pass the pointer to the member variable? Eg:

Foo myFoo;
cllabackFunction(&(myFoo.x));

This doesnt entirely strike me as a thing you really want to be doing. Still,

There is the offsetof (type,member) macro, it returns the byte offset of a field within your struct. You can use that to get the base address of the object (from the address of one of its members - if you know which member) and cast that address to the correct type.

of course, its not guaranteed to work for non-PODS, although not guaranteed doesn't mean it wont work, your ok with non-portable and potentially undefined behaviour aren't you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM