+ 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; }

17th Jul 2018, 6:05 PM
Siddharth Jain
Siddharth Jain - avatar
1 ответ
+ 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.
11th Aug 2018, 1:39 PM
Roman Khristoforov
Roman Khristoforov - avatar