By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,294 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

Pass and cast address of cast

P: 2
Can we assume member variables reside in a class as they would in a structure? It is legitimate to assume the memory layout of the field of a structure. Can we assume the same for a class?

e.g.
struct
{
long x;
long y;
} s;

char* p = (char*)&s.x;
long* q = p+4;

In memory both s.x and s.y are 4-bytes and assuming compiler packs memory then the address of s.y is the address of s.x plus 4 bytes. p points to first byte of s.x and q points to first byte of s.y.


class MyClass
{
public:
long x;
long y;
};

MyClass t;

char* p = &t.x;
char* q = p+4;

Does q point to first byte of t.y? Always?


};
Jun 2 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
Can we assume member variables reside in a class as they would in a structure? It is legitimate to assume the memory layout of the field of a structure. Can we assume the same for a class?
You may. C only has structs. C++ is a replacement for C. Therefore, C++ onlky has structs. The C++ class is an appeasment to the object technology folks who speak of classes and unless C++ has one, the impression would be that C++ can't do objects. However, the underlying implentation of a C++ class is a struct.

Rephrasing, if you declare each of your struct members as public/private/protected, there is no difference between a class and a struct.

The one difference between the two is the default access specifier. For a struct the default is public: for a class the default is private.

char* p = (char*)&s.x;
What!!! First, this is a bad cast. Second, it's a C cast and not a C++ cast. s.x is a long and no amount of fiddling will make a char.

Worse, there is a presumption that the low 8 bits of a the long is a signed char-including the sign bit.

In memory both s.x and s.y are 4-bytes and assuming compiler packs memory then
You said it yourself: assuming compiler packs... Generally, variables are laid out on int boundaries. That means there can be slack bytes. The compiler will adjust the pointer arithmetic to take this into account ---->>>>>Right up until you pull a cast and make assuptions about memory.

Therefore:
Does q point to first byte of t.y? Always?
is a definite could be.

Please do not make assumptions in C++ and especially do not cast. A cast in C++ means one of two things a) you are calling a relic C function and you have to cast to a void* or somesuch thing, or b) your C++ design is screwed up.
Jun 2 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.