Object Oriented Programming Practical 17
Question 1
Write a C++ program declare a class "polygon" having data members width and height. Derive classes "rectangle" and "triangle" from "polygon" having area() as a member function. Calculate area of triangle and rectangle using pointer to derived class object.
polygon.cpp
C
#include<iostream.h>
#include<conio.h>
class polygon
{
public:
int height,width;
void accept()
{
cout<<"\nEnter height: ";
cin>>height;
cout<<"\nEnter width: ";
cin>>width;
}
};
class reactangle:public polygon
{
public:
void area()
{
int a=height*width;
cout<<"\nArea of rectangle is: "<<a<<endl;
}
};
class triangle:public polygon
{
public:
void area()
{
int a=(height*width)/2;
cout<<"\nArea of triangle is: "<<a<<endl;
}
};
void main()
{
clrscr();
polygon p,*ptr;
reactangle r;
triangle t;
ptr=&r;
cout<<"\nEnter height and width for rectangle";
ptr->accept();
r.area();
ptr=&t;
cout<<"\nEnter height and width for triangle";
ptr->accept();
t.area();
getch();
}
Output

Question 2
Write a program which show the use of Pointer to derived class in multilevel inheritance.
derivedptr.cpp
C
#include<iostream.h>
#include<conio.h>
class Base
{
public:
virtual void show() {
cout << "Base class show function called" << endl;
}
};
class Derived1 : public Base
{
public:
void show()
{
cout << "Derived1 class show function called" << endl;
}
};
class Derived2 : public Derived1
{
public:
void show()
{
cout << "Derived2 class show function called" << endl;
}
};
int main()
{
Base *ptr;
Derived1 obj1;
Derived2 obj2;
ptr = &obj1;
ptr->show();
ptr = &obj2;
ptr->show();
getch();
return 0;
}
Output
