This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug c++/22132] New: Wrong code: upcasting a const class pointer to struct the class derives from
- From: "scott dot tupaj at line6 dot com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: 21 Jun 2005 01:35:48 -0000
- Subject: [Bug c++/22132] New: Wrong code: upcasting a const class pointer to struct the class derives from
- Reply-to: gcc-bugzilla at gcc dot gnu dot org
Upcasting a const class pointer for a class that was derived from a struct causes the upcasted pointer to
incorrectly access members of the derived struct.
Conditions:
1) The derived class object must have a virtual destructor (or possibly any v-table entries)
2) The upcast must be a straight 'C' cast that does not preserve the const.
I've attached a code sample that demonstrates the error, but this is the scenario:
struct foo {
int a;
int b;
};
class Foobar : public foo {
public:
Foobar() { a = 1; b = 2; };
virtual ~Foobar() {};
};
Foobar obj;
const Foobar* objPtr = &obj;
foo* f = (foo*)objPtr;
contents of f->a and f->b during runtime are not 1 and 2 as expected.
f->a is garbage
f->b is 1 (expected value of f->a)
--
Summary: Wrong code: upcasting a const class pointer to struct
the class derives from
Product: gcc
Version: 4.0.0
Status: UNCONFIRMED
Severity: normal
Priority: P2
Component: c++
AssignedTo: unassigned at gcc dot gnu dot org
ReportedBy: scott dot tupaj at line6 dot com
CC: gcc-bugs at gcc dot gnu dot org
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=22132