Virtual Function in C++

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.

Output

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.

Output

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.

Categories C++