WangXh
WangXh

Reputation: 49

A confusion about c++ virtual function

Just look at the following two class. When I call the functions in "main", what will happen when compiled and program running?

#include <iostream>
#include <string>
using namespace std;
class A{
public:
    virtual void fun2(){cout<<"A::fun2"<<endl;}
};
class B : public A{
public:
    void fun2(){cout<<"B::fun2"<<endl;}
};
int main() {
    A *a = new B();
    B *b = new B();
    //What's the differences among the followings?
    a->A::fun2();
    b->A::fun2();
    A::fun2();

    return 0;
}

I know what the program to print, but I wonder why. I know there is a virtual function table in the object, but when I call

a->A::fun2()

, how it works? Since in the a or b's v-table, the fun2() will print B::fun(), How does the program get into the function A::fun2()?

Upvotes: 0

Views: 219

Answers (2)

emvee
emvee

Reputation: 4449

From the moment you call a member function through an explicit scoping operator, like

instanceptr->Scope::memberfun()

it is not a virtual function call anymore. The function is just not called via the v-table mechanism anymore.

Class B in your example extends Class A but that doesn't mean that the code for the member function A::fun2() does not exist anymore - it's there, in your object file, and the compiler just calls that function directly.

Upvotes: 0

Humam Helfawi
Humam Helfawi

Reputation: 20264

a->A::fun2();

will print A::fun2


b->A::fun2();

will print A::fun2


A::fun2();

won't be compiled

Upvotes: 1

Related Questions