is python Object oriented??
db3l.net at gmail.com
Sun Feb 1 05:33:49 CET 2009
thmpsn.m.k at gmail.com writes:
> I don't know how you would do it in C# (or Java for that matter).
> In C++ you can play with pointers to "get at" some memory location
> somewhere in the object. The only portable way to know the exact
> location between the beginning of the object and the desired member is
> the offsetof() macro, but as I understand it this only works for POD
> types, which means that it won't work for classes such as:
> class NonPOD
> int a;
> int b;
> int C();
> (I haven't ever actually tried it, so I'm not sure.)
> Nevertheless, you can play and hope for the best. For example, if the
> member you want to get at is 'b', then you can do:
> NonPOD obj;
> std::cout << "obj.b = " << *(int*) ((unsigned char*) &obj + sizeof
> (int)) << std::endl;
> and hope that the compiler didn't leave a hole between the 'a' member
> and the 'b' member.
Probably moving off topic, but I don't think you have to get anywhere
near that extreme in terms of pointers, unless you're trying to deal
with instances for which you have no source but only opaque pointers.
I haven't gotten stuck having to do this myself yet, but I believe one
commmon "hack" for the sort of class you show above is to just
"#define private public" before including the header file containing
the class definition. No fiddling with pointers, offsets, or
whatever, just normal object access syntax past that point.
Of course, I believe such a redefinition violates the letter of the
C++ standard, but most preprocessors do it anyway. Also, it won't
handle the case where the "private:" is not used, but the members are
just declared prior to any other definition, since a class is private
But even then, if you had to, just make a copy of the class definition
(or heck, just define a structure if it's just data elements), ensure
the private portions are public, and then cast a pointer to the old
class instance to one of your new class instance. Assuming you're
building everything in a single compiler, the layouts should match
just fine. Again, normal object member access, no casting or pointers
needed (beyond the initial overall object pointer cast).
More information about the Python-list