Reputation: 39
I can't seem to understand how the compiler priorities to which function to go. here is an example code:
#include <iostream>
using namespace std;
class A{
public:
int f() {return 1;}
virtual int g() {return 2;}
};
class B: public A {
public:
int f() {return 3;}
virtual int g() {return 4;}
};
class C: public A{
public:
virtual int g() {return 5;}
};
int main () {
A *pa;
B b;
C c;
pa = &b;
cout<< pa -> f()<<endl<<pa -> g() << endl;
pa = &c;
cout<< pa -> f() << endl; cout<< pa -> g() << endl;
return 0;
}
to which function (g() and f()) will be called each time and why?
Upvotes: 0
Views: 291
Reputation: 7542
When you say a function is virtual
you tell the compiler to use late binding instead of static binding.
So during compile time A::f()
will be static bound so it is kind of fixed which method body to call.
On the other hand A::g()
will not be bound to any method body during compile time.It will be decided at runtime which method body to be called (using vptr).
A *pa; //no matter what object you assign to pa, A::fa() will always be called
pa = &b;
pa->f();//calls A::f()
pa->g();// remember what function body to be called will be decided at runtime.
//will call B::f()
pa = &c;
pa->g(); //will call C::g()
Upvotes: 0
Reputation: 37641
pa->f()
will always call A::f()
, whatever you make pa
points to because pa
is a A*
and A::f
is not virtual.
pa->g()
will call A::g()
, B::g()
or C::g()
depending on what pa
points to using polymorphism because A::g
is virtual:
pa
points to a B
(first sequence), it will call B::g()
.pa
points to a C
(second sequence), it will call C::g()
.Upvotes: 1
Reputation: 18855
In the first sequence it will call A::f()
and B::g()
.
In the second sequence it will call A::f()
and C::g()
.
The reason for this is that f()
as non-virtual method is resolved during compile time according to variable type (pointer to A
). g()
is marked as virtual method in A
and therefore runtime resolve is done and it will always call the method of the real instance (B
or C
).
Upvotes: 0