|
From: Jason H. <jas...@bt...> - 2001-10-20 16:49:16
|
MessageAFAICT 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.
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.
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.
I hope I have explained that OK. I'm rushing a little as I'm going out =
in a minute.
Jason.
----- Original Message -----=20
From: Ioannis Vranos=20
To: Dev-C++=20
Sent: Saturday, October 20, 2001 6:24 PM
Subject: [Dev-C++] Strange effect
Strange effect. Consider the code:=20
#include <iostream>
class A
{
public:
void test() { std::cout<<"A!\n"; }
};
class C: public A
{
public:
void test() { std::cout<<"C!\n"; }
};
int main()
{
using namespace std;
=20
A a;
=20
C *cp=3Dstatic_cast<C *>(&a);
=20
cp->test();
}
It produces
C:\c>temp
C!
Isn't this wrong? I expected either a GPF or garbage, or even "A!" but =
not "C!".
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.f2s.com
* Alternative URL: http://run.to/noicys
|