What is virtual function?
Answer:
When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.
class parent
{
void Show() {
cout << "i'm parent" << endl;
} };
class child: public parent {
void Show() {
cout << "i'm child" << endl;
} };
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls parent->show() i
now we goto virtual world...
class parent { virtual void Show() {
cout << "i'm parent" << endl;
} };
class child: public parent { void Show() {
cout << "i'm child" << endl;
} };
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls child->show()
No comments:
Post a Comment