Introduction To Classes

The C++ class

Suppose that we wish to design a rectangle object. We must decide 1) what data should be included in this object and 2) what functions are needed for this object. The data needed for this object should include a rectangle's dimensions: width and height of the rectangle. Some of the functions needed might include: a function to print a rectangle, a function to compute the area of the rectangle, a function to compute and print the perimeter of a rectangle, a function to draw a rectangle and a function to allow the user to set the length and width of the rectangle. Now we are ready to construct the class. The basic syntax is:


class name
{
public:

     //declare all functions and variables that are available 
     //to the user of the class

private:

     //declare all functions and variables that should not be 
     //available to the user
};

For example, the declaration of the rectangle class may appear as follows:


//FILE: Rectangle.h
class Rectangle
{
     public:
         Rectangle();
         Rectangle( double length, double width );	
         double getArea();
         double getPerimeter();
         void setSize( double length, double width );
 
     private:
         double length;
         double width;
};

The Rectangle class has seven members - five member functions (Two Constructors, getArea, getPerimeter and setSize) and two member variables (length and width). The member variables form the data that is needed to create a rectangle and the member functions allow the user to perform different operations with a rectangle. Note that in this example, clients (users) of this class have access to the member functions but do not have access to the member variables.

Assignment:
  1. Place the above Class Interface in a file called Rectangle.h
  2. Create a Class Definition for this class in a file called Rectangle.cc
    It should #include the Rectangle.h file, and then you should write the member functions
    for this class to function.
  3. Create a small test main, in another file, which uses the Rectangle class you've just created.