1.3 Classes and Objects


1. A class can be considered as a description of an object.
2. It provides a definition of the data and the behavior of an object which could match a real world object.
3. The class is a data type which is used to define objects.
4. It specifies what data and functions are included in objects of that class.
5. Writing a class doesn't create any objects. Objects are instances of classes.

Example: Defining a class (template) to represent points in a graphics program.

Description:
1. Points on a plane must have two properties (states): x and y coordinates. We can use two integer
variables to represent these properties.
2. Points should have the following abilities (responsibilities)
a. Points can move on the plane: move function.
b. Points can show their coordinates on the screen: print function.
c. Points can answer the question whether they are on the zero point (0,0) or not: is_zero function.

1.3 Classes and Objects


The class can be defined in C++ as shown in Listing 1.1.



Listing 1.1: Defining a Point class in C++

1. In Listing 1.1, the Point class is defined which represents real world points in the program.
2. It can be considered as a user-defined type.
3. It contains two integers x and y that represent the data (coordinates) required to define a point.
4. They are called the class attribute members.
5. The operations related to the point are also represented in the class using functions move, print and
is_zero. They are function members of the class.

1.3 Classes and Objects


6. Only function prototypes are included in the class definition in Listing 1.1. The code of function members of
the class are shown in Listing 1.2.
7. Note the operator ::, which is called the scope resolution operator. It is used to specify to what class the
member function belongs to.


1.3 Classes and Objects




Listing 1.2: Implementation of functions declared in Class Point

1. After defining Class Point, we can now define Point objects which are instances of the class.
2. The code to defining two Point objects point1 and point2 is shown in Listing 1.3.

1.3 Classes and Objects


3. All members defined in the class now belong to each of the objects defined.
4. Thus, point1 has its own x and y attributes and member functions move, display and is_zero.
5. Similarly, all members also belong to point2.
6. Note that members of the object can be accessed using the dot (.) operator.

1.3 Classes and Objects




Listing 1.3: Defining Point Objects