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.
3 odpowiedzi
+ 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.
+ 6
By keeping what is called a vtable, a table that keeps track of the addresses of all the virtual functions.
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.🤔