C++ Classes
In C++, classes are the building blocks of object-oriented programming. A class is similar to a structure, except that a class is designed to include function members, as well as data members. A well-designed class can be used as easily as a predefined data type. Instances of a class are called objects. We have used predefined classes and objects in the previous discussion. For example, we used the cin object and the cout object to perform standard input and output operations. These objects are also called functions, including precision and setf.
Defining a Class Data Type
A class definition consists of two parts: a class declaration and a class implementation.
Class declaration: the name of the class is specified using the keyword class. The body of the class declaration consists of type declaration statements for the data members and function prototypes for the function members.
class sample
{
public:
void print();
double variable();
};
Suppose we want to define a data type to represent a data point that is represented in rectangular coordinates; thus, the data type is represented by an x-coordinate and a y-coordinate, as shown below. When designing a class type, we need to consider the data members that are required to represent the new data type, as well as the operations that we would like to define for the data type.
The class design includes function members to implement the desired operations. Consider the class declaration that we present for the xy_coordinate class, which consists of
two data members to define the point and two member functions that operate on the coordinates to determine the radius r and the angle q, as at right. We will add additional member functions to the design of the xy_coordinate class later in this section. The class declaration, is typically stored in a header file, as shown in the following code:
// These statements define a class for xy-coordinates.
// This declaration is stored in xy_coordinate.h.
#include <iostream>
#include <cmath>
using namespace std;
class xy_coordinate
{
// Declare function prototypes for public members.
public:
void input();
void print();
double radius();
double angle();
private:
// Declare private data members.
double x, y;
};
The xy_coordinate class has two data members and four function members. The keywords public and private are used to control access to the members of the class.
PUBLIC: Members that are specified as public members may be referenced anywhere in the user program.
PRIVATE: Members that are specified as private members may only be referenced by member functions of the xy_coordinate class. This restricted access is known as information hiding. If modifications are made to the data representation of a class, only the member functions need to be modified; no change to the user program is required. Any private member functions can only be called by other member functions. These private member functions are often referred to as helper functions because they are designed to help the other member functions.
CLASS IMPLEMENTATION consists of all the member function definitions. When defining a member function, the scope resolution operator (::) is used in the function definition. This operator is placed between the class name and the function name to specify that the function is a member of the class. When writing a member function definition, first specify the type of value being returned by the function. The class name, the scope resolution operator, the name of the function, and the parameter list will follow. Recall that all member functions have direct access to the data members, so the data members do not appear in the parameter list. Helper functions can also be called directly by a member function. A class implementation can also be stored in a separate file.
// These statements define implementation of an
// xy_coordinate class. They are stored in xy-coordinate.h.
// This function reads the xy coordinates from the keyboard.
void xy_coordinate::input()
{
cin >> x >> y;
}
// This function prints the xy coordinates to the screen.
void xy_coordinate::print()
{
cout << "(" << x << "," << y << ")" << "\n";
}
// This function computes the radius.
double xy_coordinate::radius()
{
return sqrt(x*x + y*y);
}
// This function computes the angle in radians.
double xy_coordinate::angle()
{
// Compute angle of polar form.
double z, pi=3.141593;
if (x >= 0)
z = atan(y/x);
if (x<0 && y>0)
z = atan(y/x) + pi;
if (x<0 && y<=0)
z = atan(y/x) - pi;
if (x==0 && y==0)
z = 0;
return z;
}
We now present a program to test this new data type.
// This program demonstrates the use of
// the xy_coordinate class and its functions.
#include <iostream>
#include <cmath>
#include "xy_coordinate.h"
using namespace std;
int main(void)
{
// Declare and initialize variables.
xy_coordinate pt1;
// Read input point.
cout << "Enter x and y coordinates:" << endl;
pt1.input();
// Print coordinate in xy form and polar form.
cout.setf(ios::fixed);
cout.precision(2);
cout << "Coordinate in xy form:" << endl;
pt1.print()
cout << "Coordinate in polar form:" << endl;
cout << "magnitude: " << pt1.radius() << endl;
cout << "phase (in degrees)" << pt1.angle()*180/3.141593 << endl;
// Exit program.
return 0;
}
At this point we will have you install the DEV C++ compiler and walk you through getting this program working with the compiler.
To execute this program, you need to be sure that the xy_coordinate header file and the xy_coordinate implementation file are accessible to the compiler, along with the program file. This separation of the components allows us to build our own libraries for programmer- defined classes. These libraries can be used by many application programs in the same way that the standard libraries, such as iostream are used. The application program must include the declarations file and be linked to the implementation file. Using these files, we can now test the program. Here is a sample output from the program:
Enter x and y coordinates:
4 4
Coordinate in xy form:
(4.00,4.00)
Coordinate in polar form:
magnitude: 5.66
phase (in degrees): 45.00
Constructor Functions
When we define a variable, we often want to assign an initial value to the variable, as in
double sum=0;
If we do not initialize a variable at the time we define it, the variable holds an unknown value until valid data is assigned. Constructor functions are special member functions that are called automatically when an object of that class is declared. The constructor function is used to initialize the data members of the object being defined. When designing a class, a complete set of constructor functions should be provided. Constructor functions have three unique properties:
* a constructor is called automatically when an object of that class is declared;
* the name of a constructor function is the name of the class;
* no return value is associated with a constructor function, and it is not a void function.
To illustrate, we define two constructor functions to initialize the class members. One function initializes x and y to zero; the other initializes x and y to values in the declaration statement. The two declarations are the first ones in the public declaration list in the following code:
// These statements define a class for xy-coordinates.
// Assume that this declaration is stored in xy_coordinate.h.
// The update is the addition of two constructor functions.
#include <iostream>
#include <cmath>
using namespace std;
class xy_coordinate
{
// Declare two constructor functions and six function
// prototypes for public members.
public:
xy_coordinate();
xy_coordinate(double a, double b);
void input();
void print();
double radius();
double angle();
// Declare private data members.
private:
double x, y;
};
The default constructor is called automatically whenever an object is defined in a declaration as follows:
xy_coordinate pt1;
Thus pt1 is an object of the class xy-coordinate. The data members of the object pt1 are initialized to the values assigned by the default constructor function xy-coordinate(). The constructor function with parameters is called automatically whenever an object is defined in a declaration statement as follows:
xy_coordinate pt2(3,4);
The data members of the object pt2 will be initialized to the values passed through the parameter list using the constructor function xy-coordinate(double a, double b). Thus, x is given the value 3 and y is given the value 4.
Constructor functions are programmer-defined functions. Here are the constructor functions that should be added to the class implementation file:
// This constructor function initializes x and y to zero.
xy_coordinate::xy_coordinate()
{
x = 0;
y = 0;
}
// This constructor function initializes x and y to parameters.
xy_coordinate::xy_coordinate(double a, double b)
{
x = a;
y = b;
}
Class Operators
The assignment operator is defined for objects of the same class type. If pt1 and pt2 are both xy_coordinate objects, then this statement is a valid statement:
pt1 = pt2;
Each data member of the object pt1 is assigned the value of the corresponding data member of the object pt2. However, the C++ arithmetic operators and relational operators cannot automatically be used with a programmer-defined class type. This comparison is not valid:
if (pt1 == pt2) (invalid comparison)
A class definition can include a set of operators to be used with objects of the class. The ability to overload operators is a powerful feature in C++. Overloading operators allows a programmer-defined data type to be used as easily as any predefined data type. As an example, consider the arithmetic operators defined in C++. These operators are defined to operate on all predefined data types. However, they are not defined for objects from programmer-defined data types. When designing a class data type, a set of arithmetic operators that work on objects of the class may be included. Operators are included in a class definition in the same way as member functions, except that the keyword operator is used. It is followed by the name of the function, where the name of the function is one of the predefined C++ operators. Only predefined operators may be overloaded. You may not, for example, define a new operator ** to perform exponentiation since this operator is not one of the predefined operators in C++. Next lecture, we illustrate the use of overloaded operators in the definition of a complex number class that includes the arithmetic operators (i.e., + , -, *, /).
Homework:
Define a class to represent a date. A date is defined using three integer variables: month, day, and year. Include member function definitions to
• input a date;
• print a date as month/day/year (10/1/1999);
• print a date as month day, year (October 1, 1999);
• initialize a date object.
Write a sample program that allows the user to enter the date using the date input function and prints the data in each of the defined forms using the class member functions.
No comments:
Post a Comment