Polymorphism again

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
#include <iostream>

using namespace std;

class ClassA
{
public:
	virtual void f1(){cout<<"A:f1 \n";}
		void f2(){cout<<"A:f2 \n";}
};
class ClassB : public ClassA
{
public:
	void f1(){cout<<"B:f1 \n";}
	void f2(){cout<<"B:f2 \n";}
	void f3(){cout<<"B:f3 \n";}
};
class ClassC : public ClassB
{
public:
	void f1(){cout<<"C:f1 \n";}
	void f2(){cout<<"C:f2 \n";}
};

int main()
{
	ClassC* C = new ClassC;
	ClassB* B = C;
	ClassA* A = C;
	cout<<"A->f1, f2 \n";
	A->f1();
	A->f2();
	cout<<"B->f1, f2, f3 \n";
	B->f1();
	B->f2();
	B->f3();
	cout<<"C->f1 \n";
	C->f1();
}


OUTPUT:
A->f1, f2
C:f1
A:f2
B->f1, f2, f3
C:f1
B:f2
B:f3
C->f1
C:f1

I am trying to get a set of rules in my head that will predict any polymorphic situation. This may take a while! In the above example, I was thinking like this: if pointer of type B points to derived object C, the call B->f2 doesn't care about C::f2 because B::f2 is not virtual, so it doesn't look for any overriding functions in the C object that B is pointing to. Hence B->f2 shows B:f2. Same with call A->f2, A::f2 not virtual so A->f2 calls A::f2 even though there is in derived C a C::f2 and A is actually pointing to a C object. So far, so good, my little rule works.

But then I see B->f1 goes to the overriding C->f1, even though B::f1 is not declared as virtual. Given, it is a bad idea to mask B::f1 with C::f1, but I would not predict B->f1 would go to C->f1, especially since A-f2 does not go to C->f2.

I think I'm going to have to completely understand what happens in V tables to really understand polymorphism?
f1 is virtual in class A so all its derived classes will have it virtual so C is overriding it
I did not know this, learned something new again. So even though B::f1 does not inherit any part of the function logic in the body of A::f1, it DOES inherit the "virtual" attribute of A::f1. And that virtual attribute will propagate down through all derived, derived of derived, etc... classes, even if none of them are declared as virtual.

Is there anything else a derived function can inherit from a virtual base class function of same name and argument list, if both have different 'body of the function' definitions (other than "virtual")?
Last edited on
No, the derived class gets from its base class the declaration of the virtual function (name and argument types) which remains virtual and, if missing, it also has the same body as the base class.
thanks Bazzy!
Topic archived. No new replies allowed.