C++ 47:Polymorphism part 3

 Pure Virtual Functions / Abstract Functions

A virtual function without function definition (i.e. function body) is called as pure virtual function. The pure virtual functions are also called as abstract functions.
A pure virtual function can be defined as follws:
Syntax:
            virtual return_type function_name(data_type_of_arg1, data_type_of_arg2..) = 0;



Abstract Classes

  • If a class contains at least one pure virtual function then such class is called as abstract class.
  • An abstract class an abstract class cannot be initiated it means it is not possible to create objects of an abstract class but it is possible to create pointers abstract class
  •  It is possible to derive new classes from an abstract class but if a class derived from abstract class then the derived class we need to override all the pure virtual functions inherited from the base class otherwise the newly derived class will become an abstract class.

Example:

//Testing for Pure virtual functions

#include <iostream>
using namespace std;

class Unit
{
public:
    virtual void showData() = 0; //pure virtual function
    virtual void Convert() = 0;
};
class Distance : public Unit
{
private:
    int FI;

public:
    Distance(int f, int i)
    {
        F = f;
        I = i;
    }
    void showData()
    {
        cout << F << " feet and " << I << "Inches" << endl;
    }
    void Convert()
    {
        int z = F * 12 + I;
        cout << "Data of Distance Objectis :" << z << endl;
    }
};
class Time : public Unit
{
private:
    int MH;

public:
    Time(int h, int m)
    {
        M = m;
        H = h;
    }
    void showData()
    {
        cout << H << " Hours and " << M << " minutes" << endl;
    }
    void Convert()
    {
        int z = H * 60 + M;
        cout << "Data of Distance Objectis :" << z << endl;
    }
};

int main()
{
    Unit *p[5];

    p[0= new Distance(23);
    p[1= new Distance(45);
    p[2= new Time(34);
    p[3= new Time(45);
    p[4= new Time(86);

    //Poly morphic code
    for (int i = 0i <= 4i++)
    {
        p[i]->showData();
        p[i]->Convert();
    }

    delete p[5];

    return 0;
}

Output:

2 feet and 3Inches
Data of Distance Objectis :27
4 feet and 5Inches
Data of Distance Objectis :53
3 Hours and 4 minutes
Data of Distance Objectis :184
4 Hours and 5 minutes
Data of Distance Objectis :245
8 Hours and 6 minutes
Data of Distance Objectis :486


Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected