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?
Because there is no such member.
virtualfunctions 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 atarr[ i ]->f2()it looks up the definition ofarrfor its type.arrhas (static) typeA. So, the compiler looks upA‘s definition for a suitable definition off2and doesn’t find any. Hence the diagnostic.virtualfunctions can be safely inlined. In fact, all in-class definitions are implicitly inlined by the compiler. So, yourA::f1is already inlined.