virtual function and pure virtual function

Virtual function


A virtual function a member function which is declared within a base class and is re-defined (Override) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for the function call. They are mainly used to achieve Runtime polymorphism Functions are declared with a virtual keyword in a base class. The resolving of a function call is done at Run-time.

#include<iostream>

using namespace std;
class Base
{
public:
    virtual void print()
    {
        cout<<"Print the Base class"<<endl;
    }
    void show()
    {
        cout<<"Show base class"<<endl;
    }
};
class Derived:public Base
{
public:
    void print()
    {
        cout<<"Print derived class"<<endl;
    }
    void show()
    {
        cout<<"Show base class"<<endl;
    }
};
int main()
{
    Base* bptr;
    Derived d;
    bptr=&d;
    bptr->show();
    bptr->print();
}


Pure Virtual function

A pure virtual function implicitly makes the class it is defined for abstract. Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions.
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have the implementation.
A pure virtual function is a virtual function whose declaration ends in=0;
A class is abstract if it has at least one pure virtual function.In the following example, Test is an abstract class because it has a pure virtual function show().


#include<iostream>
using namespace std;
class Base
{
    int x;
public:
    virtual void fun()=0;
    int getx()
    {
        return x;
    }
};
class Derived:public Base
{
    int y;
public:
    void fun()
    {
        cout<<"fun called";
    }
};
int main()
{
    Derived d;
    d.fun();
    return 0;

}

Comments

Popular posts from this blog

C program that contains a string XOR each character in this string with 0 ,127

Queue in Data Structure(DS)

Implementation of stack Using Array