Monday 28 May 2012

Class Inheritance

Inheritance is the ability for one class to receive its primary functionality from another class, also called its base class.
This example uses a class called Circle so that, given a radius, the program would calculate and display the diameter, the circumference, and the area.
Another class called Sphere is derived from the Circle class. This class can supply its own radius, display the same pieces of information as the Circle. Additionally, the Sphere class should calculate and display the volume.
This exercise uses different header and source files. It uses the following five files: circle.h, circle.cpp, sphere.h, sphere.cpp and exo.cpp.
Header File: circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
struct Circle{
public: 
Circle(); 
void setRadius(double r); 
double getRadius();
 double Diameter();
 double Circumference();
 double Area();
 void Display();
protected: 
double Radius;private:
};
#endif
Source File: circle.cpp
#include <iostream.h>
#include "circle.h"
const double PI = 3.14159;
Circle::Circle()
Radius = 0;
}
void Circle::setRadius(double r)
{ Radius = r <= 0 ? 1 : r;}
double Circle::getRadius()
{ return Radius;}
double Circle::Diameter(){
 return Radius * 2;}
double Circle::Circumference()
{ return Diameter() * PI;}
double Circle::Area(){ 
return Radius * Radius * PI;}
void Circle::Display()
{ cout << "\nCircle Properties";
 cout << "\nRadius        = " << getRadius();
 cout << "\nDiameter      = " << Diameter();
 cout << "\nCircumference = " << Circumference();
 cout << "\nArea          = " << Area() << "\n";
}
Header File: sphere.h
#ifndef SPHERE_H
#define SPHERE_H
struct Sphere : public Circle
{public: 
double Volume();
 void Show();private:};
#endif
Source File: sphere.cpp
#include <iostream.h>
#include "circle.h"
#include "sphere.h"
const double PI = 3.14159;
double Sphere::Volume()
{ return Radius * Radius * Radius * PI * 4 / 3;
}void Sphere::Show(){
 cout << "\nCircle Properties";
 cout << "\nRadius        = " << getRadius(); 
cout << "\nDiameter      = " << Diameter();
 cout << "\nCircumference = " << Circumference();
 cout << "\nArea          = " << Area(); 
cout << "\nVolume        = " << Volume() << "\n\n";
}
Main File: exo.cpp
#include "circle.h"
#include "sphere.h"
void main(){ 
Circle circle; 
 // Displaying a circle using the default value of the radius 
circle.Display(); 
Circle circ; 
// A circle with a value supplied for the radius
 circ.setRadius(12.50); circ.Display(); Sphere sphere; 
 // A sphere that has its own radius, using the functions
 sphere.setRadius(8.95); // of the base class
 sphere.Show();
}

No comments:

Post a Comment