In this article Virtual Function in CPP we give the information about A function which is not actually available but still appears in some parts of the program is called Virtual Function.
Virtual Function in CPP:
A function which is not actually available but still appears in some parts of the program is called Virtual Function.
Syntax:-
class class name
{
public:
virtual void function name ()
{
………………………………………….
…………………………………………. [body of virtual function]
}
};
In C++, a virtual function is a member function that is declared inside a base class and is overridden by a derived class.
- It is declared using the virtual keyword.
- Virtual function is mainly used to achieve runtime polymorphism. That is, it is used for late binding on the function.
- The function call in this is completed in run-time.
- Virtual function ensures that the correct function is called for the object.
Rules for Virtual Function:-
- Virtual functions can never be static members.
- These cannot be friend functions of another class.
- Virtual functions must be declared in the public section of the class.
- To achieve run time polymorphism, the virtual function should be accessed using pointer.
- The prototype of virtual functions should always be the same in base class and derived class.
- A class can have a virtual destructor but it cannot have a virtual constructor.
- Virtual function must be defined in base class.
Example of Virtual function–
#include <iostream.h>
using namespace std;
class Base
{
public:
virtual void show()
{
cout << “Base class\n”;
}
};
class Derived:public Base
{
public:
void show()
{
cout << “Derived Class”;
}
}
int main()
{
Base* b;
Derived d;
b = &d;
// // virtual function, binded at runtime
b->show();
}
OUTPUT:–
Derived class
In the above program, the show() function of the base class is declared as virtual. Therefore this function can be overriden.
Pure virtual function in C++:-
A pure virtual function is a virtual function for which we do not need to write the function definition and it is just declared. It is declared by assigning 0 in the declaration.
In C++, a class that has at least one virtual function is called an abstract class.
#include<iostream.h>
using namespace std;
class B
{
public:
virtual void s() = 0; // Pure Virtual Function
};
class D:public B
{
public:
void s()
{
cout << “Virtual Function in Derived class”;
}
};
int main()
{
B *b;
D dobj;
b = &dobj;
b->s();
}
OUTPUT:–
Virtual Function in Derived class
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining