Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Pure virtual function in C++

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 507
    Comment on it

    In C++, Pure virtual method or pure virtual function is a virtual function in which virtual function does not contain a definition inside the function declaration. A pure virtual function/method is declared by assigning a function equal to 0 in declaration.

    In pure virtual function/method, notation =0 is used to indicate that the virtual function is a pure virtual function/method, and that the function/method has no body or definition.

    Syntax:-

    class Someclassname 
             {
                 public:
                 virtual void purevirtual() = 0;  // a pure virtual function
    
                  // note that there is no function body        
              };
    

    A pure virtual function/method is implemented by class which are derived from a Abstract class.Following example to demonstrate the same.

    #include<iostream.h>
    #include<conio.h>
    
    class BaseA
    {
    int x;
    public:
        virtual void fun() = 0;
        int getX() { return x; }
    };
    
    // This class ingerits from Base and implements fun()
    
    class DerivedB: public BaseA
    {
       int y;
    public:
        void fun() 
           { 
             cout << "fun() called"; 
           }
        };
    
    int main()
    {
       DerivedB d;
       d.fun();
       return 0;
    }
    

    Output:

    fun() called
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: