Virtual Function in C++
Advertisements
Virtual Function in C++
A virtual function is a member function of class that is declared within a base class and re-defined in derived class.
When you want to use same function name in both the base and derived class, then the function in base class is declared as virtual by using the virtual keyword and again re-defined this function in derived class without using virtual keyword.
Syntax
virtual return_type function_name() { ....... ....... }
Virtual Function Example
#include<iostream.h> #include<conio.h> class A { public: virtual void show() { cout<<"Hello base class"; } }; class B : public A { public: void show() { cout<<"Hello derive class"; } }; void main() { clrsct(); A aobj; B bobj; A *bptr; bptr=&aobj; bptr->show(); // call base class function bptr=&bobj; bptr->show(); // call derive class function getch(); }
Output
Hello base class Hello derive class
Google Advertisment