Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a class/struct object from the member pointer

Tags:

c++

I have C++ structure as

struct myStruct {
    int a;
    int b;
    int c;
}; 

myStruct b;
int *ptr = &b.c;

How can I get myStruct object back from ptr?

(I know I can do this using pointer arithmatic like container_Of() in C. Basically something like

reinterpret_cast<myStruct*>(reinterpret_cast<char *>(ptr) - offsetof(myStruct, c));

I am asking if there is any recommended/elegant way?)

like image 835
Methos Avatar asked Sep 02 '26 22:09

Methos


1 Answers

There's certainly no recommended way, as doing this is definitely not recommended at all in C++. This is one of those questions where the correct answer has to be "Don't do that!"

The whole reason for using C++ instead of C is that you want to encapsulate the structure of data inside classes with sensible operations defined on them, instead of allowing the whole program to have knowledge of the internal layout of data structures.

That said, the offsetof technique you describe will work on plain old data objects, because they are no different to C structs.

like image 112
Daniel Earwicker Avatar answered Sep 04 '26 11:09

Daniel Earwicker