class pointer conversion


I encountered a problem,the problem is as following:

#include<iostream>
using namespace std;
class A
{
public:
display(){cout<<"A"<<endl;}
};
class B:public A
{
public:
display(){cout<<"B"<<endl;}
};
class C:public A
{
public:
display(){cout<<"C"<<endl;}
};

void main()
{
B b;
B* pB=&b;
C* pC=(C*)pB;
pC->display();
}
The result is "C"
Why this happen? what happend inside the class object b?
at the beginning ,i think there will be slice or something like that,but maybe i'm wrong.
Please help me.
Last edited on
I don't know what your code produces, but A::display() is not declared virtual and you probably meant it to.

In any case, forcing an object of type B through a pointer of type C is just wrong. I am guessing you are calling C::display() (meaning you see "C" in the output). This happens because the methods of a class are usually "plugged" to the 'this' pointer. This code probably doesn't crash, but that's just because display() (in any of the classes) call for data from the 'this' pointer.

Finally, use [code]//Code goes here. [/code] tags to present code snippets in your posts.
How do you escape code tags like that?
the usage i have said is in mfc.
maybe you are right.
for display(), i don't mean virtual.making classes have same display name is used to show which display is invoked.
for the program ,i just dont know how it works. i want to learn the underlying mechanism.
Last edited on
@shacktar: [co[b][/b]de][/code]
@luo193

the usage i have said is in mfc.

The example you use is not something MFC ever does. You're casting between two unrelated types.

MFC does use casts to cast from a base class to a known, derived class. In your case, that would be from A -> B or A -> C, but not B -> C.

As webJose says, the only reason you code doesn't produce rubbish, or die horribly, is because the classes are all empty. If you had been using member data which was in an instance of B but not one of C, things would have been rather different!
Last edited on
Thanks for your help
Topic archived. No new replies allowed.