-3
class A
{
    int a;
public:
    A()
    {
    }
    virtual void f1()
    {
        cout<<"A "<<endl;
    }
    virtual void f2()
    {
        f1();
    }
};

class B: public A
{
    int b;
public:
    B()
    {
    }
    void f1()
    {
        cout<<"B "<<endl;
    }
};

int main(void)
{
    B obj;
    obj.f2();
}

o/p - B

I am running this code on visual stdio 2010. Please explain Why class B's function f1() is called? and why not class A's function f1().

6 Answers6

0

You are using an object of type B. Since f2() is not overridden, it calls the f2() of class A, it's super class. But since, f1() has been overridden in class B, it will call f1() of B instead of A, from f2() of A.

SoulRayder
  • 5,072
  • 6
  • 47
  • 93
0

Every call to a virtual function will do a virtual-function lookup and call the corresponding implementation.

So the call structure in your example is

obj.f2() -> Call A.f2(), because B has no overridden f2
in A.f2(), we call f1() -> This calls B.f1() because B overrides f1.

If you explicitly wish to statically call A.f1 in A.f2, use A::f1(). However, you shouldn't do that normally, because it goes against the idea of having a virtual method f1 in A.

PMF
  • 14,535
  • 3
  • 23
  • 49
0

In your A class, both f1 and f2 are virtual. This means that any subclass can override them with its own implementation. In your main function, you construct an object of type B. When you call functions on it, it will call the overriding functions in B. It does not matter who the caller of that function is - only what the type of the object is. In that case, the object is of type B. Inside A::f2() this points to an object of type B, so it will call B::f1(). This will work the same way if you have A* b = new B(); b->f2()

divinas
  • 1,787
  • 12
  • 12
0

The virtual keyword states that the method can be overridden in a dynamic manner.
Since the object is of type B, and since f1 is overridden in B, it'll be called.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

A virtual function declared in a base class automatically makes all derived class member functions of the same name also virtual even if it is not declared virtual later in the derived class. So in this context, b.f1() will be called.

But, this behavior would not occur if f1() was called from the constructor of A because at that point B would not have been constructed yet and the virtual function table not set up.

waTeim
  • 9,095
  • 2
  • 37
  • 40
0

It calls B::f1 because it overrides A::f1. You can do this to call A:s method instead:

int main(void)
{
  B obj;
  obj.f2();
  obj.A::f1();
}

Or:

virtual void f2()
{
  A::f1();
}
qstebom
  • 719
  • 4
  • 12