Class Hierarchys and virtual functions.
Feb 28, 2016 at 4:43pm UTC
I have the following code:
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
class B1
{
public :
virtual void vf();
void f();
};
class D1 : public B1
{
public :
void vf() override;
void f();
};
void B1::vf()
{
cout << "B1::vf()\n" ;
}
void B1::f()
{
cout << "B1::f()\n" ;
}
void D1::vf()
{
cout << "D1::vf()\n" ;
}
void D1::f()
{
cout << "D1::f()\n" ;
}
int main()
{
B1 bTest;
bTest.vf();
bTest.f();
cout << "\n" ;
D1 dTest;
dTest.vf();
dTest.f();
cout << "\n" ;
B1& bTestR = dTest;
bTestR.vf();
bTestR.f();
keep_window_open();
return 0;
}
When I run this, it prints:
B1::vf()
B1::f()
D1::vf()
D1::f()
D1::vf()
B1::f()
I understand the first 2 sets of output, but what exactly is going on with the reference variable for B1?
Last edited on Feb 28, 2016 at 4:44pm UTC
Feb 28, 2016 at 5:58pm UTC
f() is not virtual so only the type of the reference (or pointer) will be used to decide what function to call. The true type of the object doesn't matter.
Topic archived. No new replies allowed.