Abstract-class-and-pure-virtual-function-in-C++ .

In this session i have discussed abstract class and pure virtual function in C++ .


The abstract class do not allow you to create the object of abstract class . Abstract class is a class which contains atleast one pure virtual function . It is provide the interface for its child class . The class that inherit the abstract class must to define the pure virtual function other wise it is also become abstract class .


Pure Virtual Function

The pure virtual function is the virtual function that can not contains the body part and end with 0 .

    virtual void function()=0;
    

Abstract Class Demo :

Example : Write a program that demonstrate the use of abstract class in C++

    #include<iostream>
    using namespace std;  
    class A
    {
        public :
       virtual void sum(int x,int y)=0; // pure virtual function
        
    };
    class B : public A
    {
        public :
        void sum(int x,int y) // pure virtual function definition
        {
            int result = x + y;
            cout<<"\nSum : "<<result;
        }
        void sub(int x,int y)
        {
            int result = x - y;
            cout<<"\nSub : "<<result;
        }
    };
   
    int main()
    {
            A*obj;
            B obj1;
            obj=&obj1;
            obj->sum(20,10);
            obj1.sum(20,10);
            obj1.sub(20,10);
            return 0;
    }
    OUTPUT : Sum  : 30
             Sum  : 30
             Sub  : 10
    

Welcome to AndroidATPoint.

back image                     next image