Hi,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
using namespace std;
struct A
{
virtual void f() { cout<<"A\n"; }
};
struct B : A
{
void f() { cout<<"B\n"; }
};
int main()
{
A a;
B b;
cout<<"Example 1\n";
A& refA = a;
refA.f();
/*B& refB = b;
refB.f();*/
cout<<"Example 2\n";
refA = b;
refA.f();
cout<<"Example 3\n";
A& otherRefA = b;
otherRefA.f();
}
|
The output for this code is :
Example 1
A
Example 2
A
Example 3
B
Press any key to continue . . .
I would expect that both examples 2 & 3 will give me the same result.
I tried to figure it out but I could not.
Both are references of a base class type, that get a derived object.
Q1 : why is the difference between them ?
As I see it, its kind of a mix between pointer - which in case of virtual method that was override in derived class - would give me the derived method (e.g. "B")
and between regular object - which in case of virtual method that was override - would give me the specific method (Still "B").
So, example 2 "use" it as a regular object and example 3, "use" it as pointer.
Q2 : How should I refer to it ?
I am using VS2008.
Thanks