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

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.81k
    Comment on it

    Pure virtual function

    virtual function

    Pure Virtual Function is declared as
    Ex : virtual return_type function_name(function arguments) = 0;

    Virtual Function is declared with keyword 'virtual' at the declaration.
    Ex : virtual return_type function_name(function arguments);

    Pure-virtual functions need not be implemented in the base class, but they must be implemented in the derived classes.

     

    Example:-

    class Base {
    // ...
    virtual void f() = 0;
    // ...

     

    Virtual functions must be implemented in the base class, but they need not be implemented in their derived classes. Derived classes will automatically inherit the base class implementations of all virtual functions, but can override those functions by providing their own implementations.

     

    Example:-

    Derived d;
    Base& rb = d;
    // if Base::f() is virtual and Derived overrides it, Derived::f() will be called
    rb.f();

     

    pure virtual function is a kind of virtual functions with a specific syntax:
    class B {
    public:
    virtual void f() =0; // =0 means pure virtual
    };

    If a class has at least one pure virtual function, it will be abstract class, so instance creation is impossible.B::f() says that you should
    implement f() in derived classes:
    class D : public B {
    void f() { /* ... */ }
    };
    If you do not implement f() in D, the D is abstract class by default, because it inherits all the pure virtual functions of class B.

    virtual function is a primary tool for polymorphic bevaviour.

 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: