In a C++ programming language, A virtual function is a member function that is declared and defined within a base class and redefined by a derived class even if the number and type of argument are matching.
Rules for Virtual Function:
- A virtual function may be declared as friend for another class.
- Constructor cannot be declared as virtual, but destructor can be declared as virtual.
- Like other function virtual function can return a value.
Example: Write a program to declare virtual function and executes the same function defined in base & derived class.
Or
Write a program to use pointer for both base and derived class and call the member function. Use virtual keyword.
Or
Write a program to create a virtual function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> using namespace std; class A { // base class public: virtual void show() { cout << "\n Show of base class "; } virtual void display() { cout << "\n Display of base class "; } }; class B: public A { //derived class public: void show() { cout << "\n Show of derived class "; } void display() { cout << "\n Display of derived class "; } }; int main() { A a; B b; A * p; p = & a; // point to A p -> show(); // access A’s show() p -> display(); // access A’s display() p = & b; // point to B p -> show(); // access B’s show() p -> display(); // access B’s display() return 0; } |
Output
1 2 3 4 | Show of base class Display of base class Show of derived class Display of derived class |
Note: In the above program ‘a ‘is an object of base class A and ‘b’ is an object of derived class B.
The pointer variable ‘p’ point to the base class. In the statement “p = &a;” the address of object ‘a’ is assigned to pointer ‘p’.
Then the pointer calls the member function of class A.
Similarly, in the statement “p = &b;” the address of object ‘b’ is assigned to pointer ‘p’.
Then the pointer calls the member function of class B.
Pure Virtual Function
In a C++ programming language, A pure virtual function is a function which is declared within base class and defined by derived class.
We can declare a pure virtual function by using “virtual” keyword.
Any normal function cannot be declared as pure function. Syntax for declaration of pure virtual function:
virtual type function _name(parameter list)= 0;
Example: virtual void show () =0;
Example: Write a program to create a pure virtual function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; class A { // base class public: virtual void show() = 0; // pure virtual function }; class B: public A { //derived class public: void show() { cout << " Show of derived class "; } }; int main() { B b; b.show(); // call to B’s show() } |
Output
1 | Show of derived class |
Description: In the above program, we have declared a pure virtual function “show ()” in a base class A which is defined by derived class B.