Search code examples
c++virtual-functionsinlining

Virtual function declared in a derived class


Here I have declared another virtual function in Derived class.

#include <iostream>

using namespace std;

class A{
    string s;
    public:
    A(const string& name) : s(name){}
     virtual void f1(){cout << "f1 of base class" << endl;};
};

class B : public A{
    string p;
    public:
    B(const string& name) : A(name){}
    virtual void f2(){cout << "virtual function of derived class" << endl;}
    void f1(){cout << "f1 of derived class";}
};

int main() {
    A* arr[] = {new A("John"),new B("Bob")};
    arr[0]->f1();
    arr[1]->f1();
    arr[1]->f2();
    return 0;
}

The function call arr[1]->f2() gives the error "‘class A’ has no member named ‘f2’".I am wondering why the _vptr points to the VTABLE of base class even when B is upcasted to A.

Also I wanted to know , is inlining virtual functions safe?


Solution

  • Because there is no such member. virtual functions take place from the class where they are declared first down through all derived classes. They do not get bubbled up. When the compiler looks at arr[ i ]->f2() it looks up the definition of arr for its type. arr has (static) type A. So, the compiler looks up A's definition for a suitable definition of f2 and doesn't find any. Hence the diagnostic.

    virtual functions can be safely inlined. In fact, all in-class definitions are implicitly inlined by the compiler. So, your A::f1 is already inlined.