Monday, April 5, 2021

Abstract classes and pure virtual functions (OOP) (36)

  /*abstract classes and pure virtual functions

*********************************************/

/*abstract class is a class which contain atlest one pure virtual function in it.abstract class are

used to provide an interface for sub classes.the classes which are inheriting with abstract class

must provide the defination to the pure virtual function otherwise the inherit classes will become

an abstract classes.pure virtual function also known as the abstract function.the object of the 

abstract class cannot be created but the pointer of the abstract class can created.pure virtual 

function  are virtual function with no defination.they start with virtual function and end with=0.*/

#include<iostream>

using namespace std;

class shape

{

protected:

double width,hight;

public:

void input(double x,double y) //simple member function

{

width=x;

hight=y;

}

virtual double area()=0; //pure virtual function

};

class rectangle:public shape //inherit with shape class

{

public:

double area() //define the pure virtual function

{

return width*hight;

}

};

class triangle:public shape    //define the pure virtual function

{

public:

double area()

{

return width*hight/2;

}

};

int main()

{

shape *obj1; //making the pointer of base class shape

rectangle obj2; //making the object of rectangle class

obj1=&obj2;//pointer of shape class take the object of rectangle class

obj1->input(3.5,7.8);

cout<<"the area of the rectangle is:"<<obj1->area()<<endl;

triangle obj3;//making the object of triangle class

obj1=&obj3;//pointer of shape class take the object of triangle class

obj1->input(3.5,7.8);

cout<<"the area of the triangle is:"<<obj1->area()<<endl;

}

No comments:

Post a Comment