Pure Virtual Functions And Abstract Classes With Program

Explain Pure Virtual Functions and Abstract Classes With Example and Program 

Pure Virtual Functions and Abstract Classes :-



Pure virtual function:-

The virtual function having no body and initialized to zero is called pure virtual functions.. A class containing pure virtual function is called abstract classes or pure abstract classes. Where as all other classes without pure virtual function and which are instantiated are called as concrete classes.

1.     These are the functions that are declared as Virtual at the same time assigned to Zero value.

2.     They don’t have any definition, they are only declared and equated to Zero.

3.     If a Class contains one or more Pure Virtual functions then that Class becomes Abstract.

4.     Objects of Abstract classes can Not be created.

5.     If we Inherit an Abstract class then we have to Redefine all the Parent class Pure Virtual functions in the Child class, otherwise the Child class would also become an Abstract class.

6.      Syntax :-   virtual  function-name ( parameter list ,if any ) = 0 ;

7.     Overriding is strictly essential.



Abstract class: is an incomplete class and hence no object of such class can be created.

   The main objective of an abstract base class is to provide some behavior or characteristics to the derived classes and to create base pointer required for the achieving run time polymorphism.



Exmple: /* A pure virtual function is a virtual function with no body  */



#include<iostream.h>

#include<conio.h>

class  shape

{           public:

                        virtual void shapeof()=0;

};

class circle : public shape

{           public :

                         void shapeof()

                         {  cout<<"\nDraw circle"; }  //Method Overriding

};

class triangle : public shape

{           public :

                         void shapeof()

                         {  cout<<"\nDraw triangle"; }  //Method Overriding

};

class rect : public shape

{           public :

                         void shapeof()

                         {  cout<<"\nDraw rect"; }  //Method Overriding

};

void main()

{           clrscr();

            circle c;

            triangle t;

            rect r;

            shape  *p[3];

            p[0]=&c ;

            p[1]=&t;

            p[2]=&r;

            for(int i=0;i<3;i++)

            p[i]->shapeof();

            getch();

}

                       





 



Labels: