Objects and Classes in C++

1. Defining Classes for Objects

A class defines the properties and behaviors for objects.

Object-oriented programming (OOP) involves programming using objects. An object rep­resents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique identity, state, and behavior.

  • The state of an object (also known as propertiesor attributes) is represented by data fields with their current values. A circle object, for example, has a data field, radius, which is the property that characterizes a circle. A rectangle object, for example, has data fields, width and height, which are the properties that character­ize a rectangle.
  • The behavior of an object (also known as actions) is defined by functions. To invoke a function on an object is to ask the object to perform an action. For example, you may define a function named getArea() for circle objects. A circle object may invoke getArea() to return its area.

Objects of the same type are defined using a common class. A class is a template, blueprint, or contract that defines what an object’s data fields and functions will be. An object is an instance of a class. You can create many instances of a class. Creating an instance is referred to as instantiation. The terms object and instance are often interchangeable. The relationship between classes and objects is analogous to the relationship between apple pie recipes and apple pies. You can make as many apple pies as you want from a single recipe. Figure 9.1 shows a class named Circle and its three objects.

Figure 9.1 A class is a blueprint for creating objects.

A C++ class uses variables to define data fields and functions to define behaviors. Addi­tionally, a class provides functions of a special type, known as constructors, which are invoked when a new object is created. A constructor is a special kind of function. Constructors can perform any action, but they are designed to perform initializing actions, such as initializing the data fields of objects. Figure 9.2 shows an example of the class for Circle objects.

The illustration of class and objects in Figure 9.1 can be standardized using UML (Unified Modeling Language) notation, as shown in Figure 9.3. This is called a UML class diagram, or simply class diagram. The data field is denoted as

dataFieldName: dataFieldType

The constructor is denoted as

C1assName(parameterName: parameterType)

The function is denoted as

functionName(parameterName: parameterType): returnType

3. Example: Defining Classes and Creating Objects

Classes are definitions for objects and objects are created from classes.

Listing 9.1 is a program that demonstrates classes and objects. It constructs three circle objects with radius 1.0, 25, and 125 and displays the radius and area of each. Change the radius of the second object to 100 and display its new radius and area.

Listing 9.1 TestCircle.cpp

1 #include <iostream>
2
using namespace std;
3
4
class Circle
5 {
6   
public:
7   
// The radius of this circle
8    double radius;
9
10   
// Construct a default circle object
11    Circle()
12    {
13       radius =
1;
14    }
15
16   
// Construct a circle object
17    Circle(double newRadius)
18    {
19        radius = newRadius;
20    }
21
22   
// Return the area of this circle
23    double getArea()
24    {
25       
return radius * radius * 3.14159;
26    }
27 };
// Must place a semicolon here
28
29
int main()
30 {
31     Circle circle1(
1.0);
32     Circle circle2(
25);
33     Circle circle3(
125);
34
35     cout <<
“The area of the circle of radius ”
36        << circle1.radius << ” is ” << circle1.getArea() << endl;
37     cout <<
“The area of the circle of radius ”
38        << circle2.radius << ” is ” << circle2.getArea() << endl;
39     cout <<
“The area of the circle of radius ”
40        << circle3.radius << ” is ” << circle3.getArea() << endl;
41
42   
// Modify circle radius
43    circle2.radius = 100;
44    cout <<
“The area of the circle of radius ”
45    << circle2.radius << ” is ” << circle2.getArea() << endl;
46
47   
return 0;
48 }

The class is defined in lines 4-27. Don’t forget that the semicolon (;) in line 27 is required.

The public keyword in line 6 denotes that all data fields, constructors, and functions can be accessed from the objects of the class. If you don’t use the public keyword, the visibility is private by default. Private visibility will be introduced in Section 9.8.

The main function creates three objects named ci rcl el, ci rcl e2, and ci rcl e3 with radius 1.0, 25, and 125, respectively (lines 31-33). These objects have different radii but the same functions. Therefore, you can compute their respective areas by using the getArea() function. The data fields can be accessed via the object using circlel.radius, circle2.radius, and circl e3. radi us, respectively. The functions are invoked using ci rcl e1. getArea(), ci rcl e2. getArea(), and ci rcl e3. getArea(), respectively.

These three objects are independent. The radius of circle2 is changed to 100 in line 43. The object’s new radius and area are displayed in lines 44-45.

As another example, consider TV sets. Each TV is an object with state (current channel, current volume level, power on or off) and behaviors (change channels, adjust volume, turn on/off). You can use a class to model TV sets. The UML diagram for the class is shown in Figure 9.4.

Listing 9.2 gives a program that defines the TV class and uses the TV class to create two objects

Listing 9.2 TV.cpp

1 #include <iostream>
2
using namespace std;
3
4
class TV
5 {
6     
public:

7     int channel;
8     
int volumeLevel; // Default volume level is 1
9     bool on; // By default TV is off
10
11    TV()
12    {
13        channel =
1; // Default channel is 1
14        volumeLevel = 1; // Default volume level is 1
15        on = false; // By default TV is off
16    }
17
18   
void turnOn()
19    {
20        on =
true;
21    }
22
23   
void turnOff()
24    {
25        on =
false;
26    }
27
28   
void setChannel(int newChannel)
29    {
30       
if (on && newChannel >= 1 && newChannel <= 120)
31        channel = newChannel;
32    }
33
34   
void setVolume(int newVolumeLevel)
35    {
36       
if (on && newVolumeLevel >= 1 && newVolumeLevel <= 7)
37        volumeLevel = newVolumeLevel;
38     }
39
40   
void channelUp()
41    {
42       
if (on && channel < 120)
43        channel++;
44    }
45
46   
void channelDown()
47    {
48       
if (on && channel > 1)
49        channel–;
50    }
51
52   
void volumeUp()
53    {
54       
if (on && volumeLevel < 7)
55        volumeLevel++;
56    }
57
58   
void volumeDown()
59    {
60       
if (on && volumeLevel > 1)
61        volumeLevel–;
62    }
63 };
64
65
int main()
66 {

67    TV tv1;
68    tv1.turnOn();
69    tv1.setChannel(
30);
70    tv1.setVolume(
3);
71
72    TV tv2;
73    tv2.turnOn();
74    tv2.channelUp();
75    tv2.channelUp();
76    tv2.volumeUp();
77
78    cout <<
“tv1’s channel is ” << tv1.channel
79       <<
” and volume level is ” << tv1.volumeLevel << endl;
80    cout <<
“tv2’s channel is ” << tv2.channel
81       <<
” and volume level is ” << tv2.volumeLevel << endl;
82
83   
return 0;
84 }

Note that the channel and volume level are not changed if the TV is not on. Before changing a channel or volume level, the current values are checked to ensure that the channel and volume level are within the correct range.

The program creates two objects in lines 67 and 72, and invokes the functions on the objects to perform actions for setting channels and volume levels and for increasing channels and volumes. The program displays the state of the objects in lines 78-81. The functions are invoked using a syntax such as tv1.turnOn() (line 68). The data fields are accessed using a syntax such as tvl.channel (line 78).

These examples have given you a glimpse of classes and objects. You may have many questions about constructors and objects, accessing data fields and invoking objects’ func­tions. The sections that follow discuss these issues in detail.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *