24 Nov 2019

  • November 24, 2019
  • Amitraj
Abstract Class and Pure Virtual Function in C++

-> An Abstract class is one that is not used to create objects.An abstract class is designed only to act as a base class.

-> Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become abstract class.

-> The form of using Abstract class is shown below:

     class  vehicle
{
              private:
                         datatype  d1;
                         datatype  d2;
              public:
                        virtual  void  spec() = 0;    // Pure virtual function
};


-> A pure virtual function is a function declared in the base class that has no definition relative to the base class.in such cases, the compiler requires each derived class to either define the function or redeclare it as a pure virtual function.

-> A pure virtual function is one which must be overriden by any concreate (i.e. non-abstract) derived class. This is indicated in the declaration with the syntax "=0" in the member function declaration.


// C++ program to demonstrate Abstract pure class.



#include<iostream>
using namespace std;
class Base        // Abstract base class
{
    public:
    virtual void show() = 0;     //Pure Virtual Function
};

void Base :: show()     //Pure Virtual definition
{
    cout << "Pure Virtual definition\n";
}

class Derived:public Base
{
    public:
    void show()
    { 
        cout << "C++ is  object oriented language\n"; 
    }
};

int main()
{
    Base *b;
    Derived d;
    b = &d;
    b->show();

}

OUTPUT:

C++ is  object oriented language




Translate

Popular Posts