on Leave a Comment

C++ Abstract Classes and Pure Virtual Functions

Pure Virtual Functions

Pure virtual functions are the function declared with virtual keyword and having no definition. Pure virtual function is also known as do-nothing function. If a class contains at least one pure virtual function, then object of that class can't be created. If we trying to create object of that class, then we get compile time error. Then the only use of that class is to create its derived class or sub class. But if we make sub class of that class (containing at least one pure virtual function), then pure virtual functions are also inherited to derived, and then if we create object of that derived class, then we again get compile time error. The only way is to override pure virtual functions in derived class.

Syntax of Pure Virtual Function

virtual void <function-name> () = 0;

Abstract Class

Abstract class is a class containing at least one pure virtual function. It is important to know that c++ has no any abstract keyword.

Key Points of Abstract Class

(1) Abstract class must contains at least one pure virtual function.

(2) Since abstract class contains pure function functions and these functions has no definition, so we can't make objects of abstract class. If we trying to create objects of abstract class, then we get compile time error

(3) For the usage of abstract class we must create derived class of abstract class.

(4) All the pure virtual functions of abstract class must be overrided in  its derived class. If any of the pure virtual function is not overrided in its base class, then the derived class is also known as abstract class and objects of that derived class can't be created too.

(5) We can make pointers of abstract class. But we can not make reference variables of abstract class. 

Example of Abstract class

#include<iostream>
using namespace std;
class Base
{
public:
    virtual void display()=0;  //Pure virtual function
};
class Derived: public Base
{
public:
    void display()
    {
        cout<<"\nI am in derived class\n";
    }
};
int main()
{
    Base *ptr;
    Derived o1;
    o1.display();
    cout<<"\nNow base class pointer containing address of derived class object\n";
    ptr = &o1;
    ptr -> display();
    return 0;
}

OUTPUT:

I am in derived class

Now base class pointer containing address of derived class object

I am in derived class

Use of Pure Virtual Function  

In a large program, sometime many functions in different classes are working same. For example, there are two classes student and employee, both classes has same function namely "setName()". So we can create a abstract class having pure virtual function namely "setName()" and we make student and employee its derived class. In derived classes student and employee, it is necessary to override setName() (Pure virtual function) and programmer will know that setName() function is necessary in both classes student and employee. 

0 comments:

Post a Comment