0

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?

user107761
  • 39
  • 2
  • 8
  • 2
    Run the program to find out and report back here if you cannot figure out *why* the code behaves as it does. But first, try to explain yourself, using your knowledge about virtual dispatch. – eerorika Jun 29 '16 at 13:37
  • I ran it, the question was the why... – user107761 Jun 29 '16 at 13:45
  • 1
    If you ran it, then surely you know which function was called, do you not? You did ask that. – eerorika Jun 29 '16 at 13:48
  • 1
    you are actually are asking two questions which? and why?. If you already know the answer to the first, then better dont ask. I made a similar mistake recently and it really adds lots of unnecessary confusion. Always better to have one question per question even if they seem so closely related – 463035818_is_not_an_ai Jun 29 '16 at 13:56

3 Answers3

1

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:

  • If pa points to a B (first sequence), it will call B::g().
  • If pa points to a C (second sequence), it will call C::g().
Community
  • 1
  • 1
Holt
  • 36,600
  • 7
  • 92
  • 139
0

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).

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
0

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()
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34