Possible Duplicate:
What is the slicing problem in C++?
I’ve got a simple code as a example of polymorphism and inheritance
class A
{
public:
int fieldInA;
void virtual overloadedFunc()
{
printf("You are in A\n");
}
};
class B : public A
{
public:
int fieldInB;
void overloadedFunc()
{
printf("You are in B\n");
}
};
void DoSmth(A* a)
{
a->overloadedFunc();
}
void DoSmthElse(A a)
{
a.overloadedFunc();
}
int _tmain(int argc, _TCHAR* argv[])
{
B *b1 = new B();
B b2;
//Breakpoint here
DoSmth(b1);
DoSmthElse(b2);
scanf("%*s");
return 0;
}
When I stop in breakpoint, the values of _vfptr[0] of b1 and _vfptr[0] of b2 are the same (SomeAddr(B::overloadedFunc(void))).
After passing b1 as parameter in DoSmth(), _vfptr[0] of local variable a is still someAddr(B::overloadedFunc(void)), but _vfptr[0] of a in DoSmthElse is now someAddr(A::overloadedFunc(void)). I’m sure this is some my misunderstaning of function overloading concept, but I couldn’t understand, why in first case I saw “You are in B” and in second “You are in A”. The same with A *b1 = new B(); DoSmth(b1); // You are in B, why?
First off, you need to get your terminology right! You didn’t overload any functions, you overrode them:
virtual) function and you replace the function being called with a function applicable to object of a more specialized class. You override the original meaning. Choosing the correct override is a run-time operation, in C++ using something similar to a virtual function table.The terms are confusing enough and to make things worse, these even interact: At compile time the correct overload is chosen which way end up calling virtual function which may, thus, be overridden. Also, overrides a derived class may hide overloads otherwise inherited from the base class. All this may make no sense if you can’t get the terms straight, though!
Now, for your actual problem, when you call
DoSmthElse()you pass your objectb2by value to a function taking an object of typeA. This creates an object of typeAby copying theAsubobject of yourBobject. But sinceBis derived fromA, not all ofBgets represented, i.e., theAobject you see inDoSmthElse()doesn’t behave like aBobject but like anAobject. After all, it is anAobject and not aB! This process is typically called slicing: you slice off the parts of theBobject which made it special.