What is pure virtual function in C++ ?



What is pure virtual function in C++ ?

    • A virtual function will become pure virtual function when you append "=0" at the end of declaration of virtual function.
    • Pure virtual function doesn't have body or implementation. We must implement all pure virtual functions in derived class.
    •  What is pure virtual function in C++

      What is pure virtual function in C++

    • Pure virtual function is also known as abstract function.
    • A class with at least one pure virtual function or abstract function is called abstract class. We can't create an object of abstract class. Member functions of abstract class will be invoked by derived class object.
      pure virtual function

    pure virtual function

    Sample Code

    #include<iostream.h>
           #include<conio.h>
    
           class BaseClass       //Abstract class
           {
    
                  public:
                   virtual void Display1()=0;     //Pure virtual function or abstract function
                   virtual void Display2()=0;     //Pure virtual function or abstract function
    
                   void Method3()
                   {
                          cout<<"\n\tMethod3() is Base Class";
                   }
    
           };
    
           class DerivedClass : public BaseClass
           {
    
                  public:
                   void Method1()
                   {
                          cout<<"\n\tMethod1() is Derived Class";
                   }
    
                   void Method2()
                   {
                          cout<<"\n\tMethod2() is Derived Class";
                   }
    
           };
    
           void main()
           {
    
                  DerivedClass D;
    
                  D.Method1();            // This will invoke Method1() Derived Class
                  D.Method2();            // This will invoke Method2() Derived Class
                  D.Method3();            // This will invoke Method3() Base Class
    
           }
    
    

    Output

    Method1() is Derived Class
    Method2() is Derived Class
    Method3() is Base Class
    

    Related Searches to What is pure virtual function in C++ ?