The truth is in a class hierarchy of several levels if we want a function at any level to be called through a base class pointer then the function must be declared as virtual in the base class but defining it as virtual in any intermediate class won’t work
#include <iostream> using namespace std; class base { public: virtual void fun1() { cout<<endl<<"in base::fun1"; } }; class derived:public base { public: void fun1() { cout<<endl<<"in derived::fun1"; } void fun2() { cout<<endl<<"in derived::fun2"; } }; int main() { base *ptr1, *ptr2; base b; derived d; ptr1=&b; ptr2=&d; ptr1->fun1(); ptr2->fun1(); ptr2->fun2();// ERROR//use((derived*)ptr2)->fun2(); return 0; }
The problem here is that the compiler is working only with a pointer to a base class object
In reality, the base class doesn’t have the fun2() function so, the compiler cannot allow a call to fun2()
which means the compiler will not know that you are working with a derived object if it has only a pointer to a base class object
As can be seen, the compiler reports an error for the below statement
ptr2->fun2();// ERROR
If the base class doesn’t have the fun2() then the compiler will not know that you are working with a derived object when it has only a pointer to a base class object
However, you can remove this error message by casting the base class pointer
((derived*)ptr2)->fun2();
Leave a Reply