Classes: Creating classes

We will start our discussion of classes with a very simple rectangle class. For this first example, we will put all of the code in one file. However, we will soon change this. It is important to understand this example before proceeding.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//A very simple class
#include<iostream>
using namespace std;
//Rectangle class declaration
class Rectangle {
    private:
        double width; 
        double length;
    public: 
        Rectangle();  //constructor
        Rectangle(double, double); //constructor
        void setWidth(double);
        void setLength(double);
        double getWidth() const;
        double getLength() const;
        double area() const;
};
Rectangle::Rectangle() {
    width=1;
    length=1;
} //constructor
Rectangle::Rectangle(double w, double l) {
    width=w;
    length=l;
} //constructor
void Rectangle::setWidth(double w) {
    width=w;
} //setWidth
void Rectangle::setLength(double l) {
    length=l;
} //setLength
double Rectangle::getWidth() const{
    return width;
} //getWidth
double Rectangle:: getLength() const{
    return length;
} //getWidth
double Rectangle::area() const{
    return width*length;
} //getArea
int main() {
    Rectangle box;  //box is an instance of Rectangle class
    box.setWidth(5); //set member attribute width
    box.setLength(8); //set member attribute length
    Rectangle crate;  //crate is an instance of Rectangle class 1x1
    Rectangle carton(3,6); //carton is declared using constructor 3x6
    cout<<"Area of box is "<<box.area()<<endl;  //prints 40
    cout<<"Area of carton is "<<carton.area()<<endl; //prints 18
    cout<<"Area of crate is "<<crate.area()<<endl; //prints 1
    system("pause");
    return 0;
} //main
CODE
rectangle1

Explanation:

  • Classes usually make the access members (variables) private so that we have more control over the values that they might hold. We have made length and width private. The user of the class (another programmer) can change the values of the variables using get and set functions. See the methods (functions) setWidth and getWidth.
  • Every class has at least one constructor that is used to create a new instance of the class. This is equivalent to being able to declare a variable with or without an initial value. In the rectangle class, we have constructors to declare an instance with no arguments, 1 double or two doubles. You can see these constructors used in lines 42, 45 and 46.

NEXT: Expanding on the rectangle class