|
This thread is locked; no one can reply to it. |
1
2
|
fread/fwrite problems! |
Karadoc ~~
Member #2,749
September 2002
|
Yes, members of structs are never reordered; polymorphism in C relies on it! struct BASE_CLASS { int a, b, c; }; struct DERIVED_CLASS { int a, b, c; float extra_data; }; Polymorhism in C is done by type casting to and from stuff that looks like that. eg. float my_function(struct BASE_CLASS *foo) { float bar = foo->a * foo->b; if (foo->c == 5) { bar*=((DERIVED_CLASS*)foo)->extra_data; } return bar; }
----------- |
Michael Jensen
Member #2,870
October 2002
|
Erm that doesn't seem relibable. Did I miss something or is the struct automatically padded? And how much padding is it safe to rely on, is there?
How can one be gauranteed that enough padding will be added?
|
HoHo
Member #4,534
April 2004
|
That one definitely shouldn't work. If it compiles then it should segfault if you try writing to the char array __________ |
Bob
Free Market Evangelist
September 2000
|
Quote: Since doubles/floats are defined specifically by IEEE, why arn't they platform/etc dependant? In addition to what gillius said, not all computers use IEEE floats. -- |
Michael Jensen
Member #2,870
October 2002
|
Quote: should segfault Right, that's what I'd expact. By those principals -- Why can what Karadoc~~ posted be guaranteed to work?
|
da_flo
Member #1,907
February 2002
|
Karadoc~~'s code is garanteed to work if c==5 only the type of the object is DERIVED_CLASS. It would be more clear if the variable was named 'type'. It's just a matter of design. It's up to the programmer to ensure the types are right. |
Michael Jensen
Member #2,870
October 2002
|
Quote: if (foo->c == 5) Ahh, I didn't see that before.
|
Evert
Member #794
November 2000
|
Quote: Why can what Karadoc~~ posted be guaranteed to work? You can acces the elements common to sta and stb, but you cannot acces elements specific to stb by casting sta to stb. Think about it: sta is the base, stb is a derived. |
Michael Jensen
Member #2,870
October 2002
|
Right that's what I thought, then I saw Karadocs code and I thought he was implying that you could -- I didn't see the c==5 thing....
|
|
1
2
|