what's the need of virtual function, please tell me as soon
need of vfunction
Collapse
X
-
Tags: None
-
In C++ you can have inheritance. There you have the base class and the derived class.
The derived class can override a base class method. So, when you use a deirved object, you call the derived method and when you have a base object you call the base method.
However, since the derived object IS-A-KIND-OF base object (due to inheritance), you can use the derived object in place of a base object.
That means you can use the derived object to call a function expecting a base object. Like this:
[code=cpp]
void Show(Base& s)
{
s.draw();
}
int main()
{
Derived obj;
Show(obj);
}
[/code]
When you are inside the Show function, you see a call to a Base class draw() method. That will call the base class draw() method when, in fact, it should be the derived class draw() method that is called since the object really is a derived object.
The compiler has a choice. It can call the Base draw() method since the Show function argument is a Base class reference, or it can call the derived class draw() method since the object is really a derived object.
You tell the compiler to call the derived class draw() method by making the base class draw() method virtual. Otherwise, the compiler will call the base class draw() method.
In other words, virtual functions is how object-oriented programming is implemented in C++.
Comment