In a C++ class, the visibility of class members is, by default, private. That is, member variables are accessible only to member functions of the class. If the member functions are to have visibility beyond the class, you must explicitly specify that visibility.
The conversion of the last program’s structure to a true C++ class is simple and straightforward. First, the struct keyword is replaced by the class keyword. Second, the member functions that are to have public visibility are separated from the private section of the class with the use of a public declaration. Examine the complete program:
// // tclass.cpp // C++ program illustrates a simple but true class and // introduces the concept of private and public. // This program uses a class to obtain the trigonometric // value for given angle. // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
main( ) { // set angle to 25.0 degrees deg.set_value(25.0);
cout << “The sine of the angle is: ” << deg.get_sine( ) << endl; cout << “The cosine of the angle is: ” << deg.get_cosine( ) << endl; cout << “The tangent of the angle is: ” << deg.get_tangent( ) << endl; cout << “The secant of the angle is: ” << deg.get_secant( ) << endl; cout << “The cosecant of the angle is: ” << deg.get_cosecant( ) << endl; cout << “The cotangent of the angle is: ” << deg.get_cotangent( ) << endl; return (0); }
In this example, the body of the program remains the same. The structure definition has been converted to a true, but elementary, class definition with private and public parts.
Note that the variable, data_value, is private to the class (by default) and as a result is accessible only by the member functions of the class. The member functions themselves have been declared public in visibility and are accessible from outside the class. Each class member, however, whether public or private, has access to all other class members, public or private.
Here is the output from the program:
The sine of the angle is: 0.422618 The cosine of the angle is: 0.906308 The tangent of the angle is: 0.466308 The secant of the angle is: 2.3662 The cosecant of the angle is: 1.10338 The cotangent of the angle is: 2.14451
Again, class member functions are usually defined immediately after the class has been defined and before the main( ) function of the program. Nonmember class functions are still defined after the function main( ) and are prototyped in the normal fashion. The next chapter examines the details of C++ classes more closely.