Need of virtual function? Why we use virtual function in c++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Need of virtual function? Why we use virtual function in c++?

Anybody clear me about virtual function . Actually I am not understand why we use and how we use. please tell me somebody in detail.

7th May 2017, 8:51 AM
Rajesh Kumar (Rj)
Rajesh Kumar (Rj) - avatar
3 Answers
+ 7
Suppose you have a class : class 3dObject { public: virtual float Volume() { return 0.0f; } }; and 2 classes that derive from it class Cube : public 3dObject { float c; public: float Volume() { return c*c*c; } }; class Sphere : public 3dObject { float radius; public: float Volume() { return radius; } // not correct volume but this is just an example }; And you have object pointers defined like this: Sphere s; Cube c; 3dObject *o1 = &s; 3dObject *o2 = &c; float v1 = o1->Volume(); float v2 = o2->Volume(); How will the program know which Volume() to call for o1 and o2? Since it is being called dynamically at run time using a pointer, the function needs to be declared virtual in 3dObject so that the right function be called.
7th May 2017, 9:12 AM
Karl T.
Karl T. - avatar
+ 6
By keeping what is called a vtable, a table that keeps track of the addresses of all the virtual functions.
7th May 2017, 9:21 AM
Karl T.
Karl T. - avatar
0
still I am confused little bit. when we declared same function virtual in base class. and two class inherit from it and both use Same function. but how virtual helping​ to identify which fiction call by main.🤔
7th May 2017, 9:17 AM
Rajesh Kumar (Rj)
Rajesh Kumar (Rj) - avatar