Gold University of Minnesota M. Skip to main content.University of Minnesota. Home page.
 
 
 

What's inside.

Ta Email

Download Compiler

Final Project

Lab Notes

Office Hours

Schedule

Syllabus

Announcements

Check Grades

 

CSci 1113 Home

 
 

Printer-friendly version

 
Inheritance - Derive a Cylinder Class from the Circle Class

Class Declaration


// Derived Class Cylinder

class Cylinder : public Circle
{
  friend double Volume(Cylinder &);
 
  protected:
    double height;

  public:
    Cylinder();
    Cylinder(int x, int y, double r, double h);
    void showdata( ostream &) const; // redefined
    double area() const; // redefined
};


Class Implementation

% cat cylinder.cpp
// Cylinder class implementation - file cylinder.cpp

#include<iostream>
#include<iomanip>
using namespace std;

#include "circle.h" // header file
#include "cylinder.h"

// constructors

Cylinder::Cylinder() : Circle(), height(1.0) {} // call base class constructor

Cylinder::Cylinder(int x, int y, double r, double h)
  : Circle( x, y, r) // initialization section- call base class constructor
{
   height = h;
}

void Cylinder::showdata( ostream & out ) const//

   out << "The cylinder's base is "
       << "\n  xcenter = " << xcenter
       << "\n  ycenter = " << ycenter
       << "\n  radius = " << radius << endl;

   out << "cylinder height = " << height << endl;
}

double Cylinder::area() const
{
  // surface area of cylinder
  return 2.0*PI*radius*radius + 2.0*PI*radius*height;
}

// friend function

double Volume(Cylinder& cyl)
{
  return cyl.PI * cyl.radius * cyl.radius * cyl.height;
}


Driver Function and Execution

% cat cylin.cpp
#include <iostream>
using namespace std;
#include <iomanip>

#include "circle.h"
#include "cylinder.h"

int main()
{

   // declare cylinder object cx

   Cylinder cx(1,1,2.0,4.0);
   cx.showdata( cout );  

   cout << "Area = " << cx.area() << endl;
   cout << "Volume = " << Volume(cx) << endl;

   return 0;
}

% g++ cylin.cpp circle.cpp cylinder.cpp
% a.out
The cylinder's base is
  xcenter = 1
  ycenter = 1
  radius = 2
cylinder height = 4
Area = 75.3982
Volume = 50.2654



 
The University of Minnesota is an equal opportunity educator and employer.
CSci 1113: C++ Programming