+ 1
virtual function and late binding
#include<iostream> using namespace std; class A { int a; public: virtual void fun1() { cout<<"class A fun1 works "; } }; class B: public A { int b; public: void fun1() { cout<<"class B fun1 works"; } /*virtual*/ void fun2() { cout<<"class B fun2 works"; } }; void fun(); void fun() { A *c=new B; c->fun1(); c->fun2();// why this line is giving error does c doesnt store the address of object B even after makinf fun2 virtual plz explain } int main() { fun(); return 0; }
1 Answer
+ 1
You need to add virtual version of fun2 to A or non-virtual, but in case of calling from pointer to A, program will call fun2 for A class, not for B. In your program not able to find entry for fun2 in vtable for class A.