|
From: Ioannis V. <no...@ya...> - 2001-10-20 17:36:41
|
At first, this result comes from both dev-c++ and bcc32. We should not see "C!" even if the member functions were virtual since we have an object A, not C assigned to A * (that's why a dynamic_cast would fail). Also every object has (must have) its own member function so there is not "only one method in memory" as you mention. Yours is the case of *static* member functions. Probably we have here some compiler optimization being confused by casting. This is definately a compiler defect(for both of them). =20 =20 Ioannis =20 * Ioannis Vranos * Programming pages: http://www.noicys.f2s.com <http://www.noicys.f2s.com/>=20 * Alternative URL: http://run.to/noicys -----Original Message----- From: dev...@li... [mailto:dev...@li...] On Behalf Of Jason Hardman Sent: Saturday, October 20, 2001 6:49 PM To: Dev-C++ Subject: Re: [Dev-C++] Strange effect AFAICT a static_cast will always be able to cast a pointer from a base into a derived type without checking if it's OK to do so as dynamic_cast would. =20 Also of note is that the methods are not virtual, so the test in C would hide the test in A. And as neither objects contains any data then there is no real difference between them. If I had more time I would try out a few things, like making the methods virtual and adding variables to the objects, i.e. private: int data; initialised differently in each object, with a getter function the same in each class. =20 When multiple instances of an object is created there is still only one method in memory, which is passed a this pointer to the object it is operating on. So in the case of this example there are two methods defined, and when you cast into the C type the compiler directs to the C method as opposed to the A method. If you tried to access data that existed in C but not A then you would get errors. =20 I hope I have explained that OK. I'm rushing a little as I'm going out in a minute. =20 Jason. ----- Original Message -----=20 From: Ioannis Vranos <mailto:no...@ya...> =20 To: Dev-C++ <mailto:dev...@li...> =20 Sent: Saturday, October 20, 2001 6:24 PM Subject: [Dev-C++] Strange effect Strange effect. Consider the code:=20 =20 #include <iostream> =20 class A { public: void test() { std::cout<<"A!\n"; } }; =20 class C: public A { public: void test() { std::cout<<"C!\n"; } }; =20 =20 =20 int main() { using namespace std; =20 A a; =20 C *cp=3Dstatic_cast<C *>(&a); =20 cp->test(); =20 } =20 =20 It produces =20 C:\c>temp C! =20 Isn't this wrong? I expected either a GPF or garbage, or even "A!" but not "C!". =20 =20 Ioannis =20 * Ioannis Vranos * Programming pages: http://www.noicys.f2s.com <http://www.noicys.f2s.com/>=20 * Alternative URL: http://run.to/noicys =20 |