Lab8 Inheritance 2
Lab8 Inheritance 2
int main() {
CRectangle rect ;
Box box;
rect.set_width(3);
rect.set_length(4);
box.set_width(3); //inherited
box.set_length(4); //inherited
box.set_height(5);
cout << "Rectangle area: " << rect.area() << endl;
1
cout << "Box base area: " << box.area() << endl; // inherited
cout << "Box volume: " << box.volume() << endl;
return 0 ;
}
Example 2: Inheritance #2: Protected data in the BASE class:
#include <iostream>
using namespace std ;
class CRectangle
{
protected:
int width, length ;
public:
void set_width (int w)
{ width=w; }
void set_length (int l)
{ length=l; }
int area ()
{ return (width*length); }
};
int main(){
CRectangle rect;
Box box;
rect.set_width(3);
rect.set_length(4);
box.set_width(3);
2
box.set_length(4);
box.set_height(5);
cout << "Rectangle area: " << rect.area() << endl;
cout << "Box base area: " << box.area() << endl;
cout << "Box volume: " << box.volume() << endl;
return 0 ;
}
3
return(PI * radius * radius) ;
}
// class declaration section where Cylinder is derived
from Circle
class Cylinder : public Circle
{
protected:
double length ; // add one data member and
public: // two member functions
Cylinder(double r = 1.0, double l = 1.0)
{
radius = r ;
length = l ;
}
double calcval() ;
};
// class implementation section for Cylinder
double Cylinder::calcval() // calculates a volume
{
return (length * Circle::calcval()) ; // note the base function call
}
int main()
{
Circle Circle_1, Circle_2(2) ; // create two Circle objects
Cylinder Cylinder_1(3,4) ; // create one Cylinder object
cout << "The area of Circle_1 is " << Circle_1.calcval() << endl ;
cout << "The area of Circle_2 is " << Circle_2.calcval() << endl ;
cout << "The volume of Cylinder_1 is " << Cylinder_1.calcval() << endl ;
return 0;
4
}