7.1 INTRODUCTION The object-oriented programming concept uses the fact that a program consists of a group of objects that may have some relationships among them. With C++, we can form objects by using the new data type called class. Object oriented programming and its applications are structurally and fundamentally built, from the ground up, using this new design philosophy. 7.2 WHAT IS A CLASS ? The concept of a class is best understood with an analogy. Out of the several objects in a room, let us talk about the picture on the wall. There is a class, which we can call the class of "Pictures" of which the picture on the wall is called an instance in C++ terminology, which in plain terms is an example. The picture in the room belongs to the class of pictures, which contains all pictures everywhere. Thus in C++, it is said "an object is an instance of a class", which means in our example that the "picture on the wall is an occurrence of the idea picture." Another example is a chair on which I am sitting. We can call it "Mychair". The chair across the room is also an object. We can call this second chair "Herchair." Both these objects share cer- tain common characteristics or attributes (and associated actions which enable them to be recog- nized as belonging to a single Chair Class). Thus Mychair and Herchair are two examples (instances) of the Chair Class but they exist independent of each other and the values of their characteristics or attributes differ. For example they occupy different positions in the room, their colours are different. Thus "Chair" is a class, but MyChair and HerChair are objects. 7.3 WHAT IS AN OBJECT ? Expressed in the laymans language, an object is something that has a fixed shape or a well defined boundary. If you look at your computer desk, you would notice several objects of varying descriptions. They may be connected to, or related to, adjacent objects. For example, a keyboard may be attached to a PC, and it is also easy to see that different parts of a PC are distinct objects. You will observe two characteristics about objects. Firstly, each object has certain distinctions or attributes which enable you to recognize and classify it. For example, a chair has four legs, a seat, and a back rest. Secondly, each object has certain actions associated with it. For example, a chair declared as an object, can be moved from one place to another. bpbonline all rights reserved 158 Programming in C++ Part I In C++, an object is a collection of related variables and functions bound together to form a higher-level entity. The variables define the state of the object, while the functions or methods define the actions that can be performed on the object. For example, a plastic scale is an object. It can be used to scale (measure) as well as draw lines. So the object scale can be used for two functions measure and draw lines. C++ programming language involves building a program or a system from objects, in the same way that we might build a car from its components. We may have to build some of these software objects ourselves, while others may be available to us from a library we have at our disposal. Thus we can think of a program as being constructed from a set of interrelated parts (modules) which activate each other by sending messages (information) to one other. Hence when a program in C++ is running, it works with components (modules) sending code to other components (modules) and causing them to execute. An object can be constructed, destroyed, and copied onto another object. It can also allocate a new object. This is achieved by using constructors and destructors. It determines how the objects of a class are created, initialized, copied, and destroyed. Thus, object-oriented programming is a technique for writing good programs for a set of problems. 7.4 OBJECTS DECLARED AS A CLASS In C++ programming, a class is a definition from which objects can be created. An example would be a "customer" class consisting of the definition of customer data and the processes which can act on it. This brings together data and all the processes which may act on it into a single unit. An individual object would have values defined for Customer Identification (ID), Name, and Address. When the Customer class receives a message (namely, delete customer), it would activate the cor- responding method to do this action. 7.5 DEFINITION OF CLASS A class is a user defined data type which holds both the data and function. The internal data of a class is called member data and the functions are called member functions. The member functions are mainly used to manipulate the internal data of a class. The variables of a class are called objects or instances of a class. A class acts like an independent program that logically organizes data and functions together. A collection of classes makes up a larger program. Classes offer three levels of accessibility, namely private, protected, and public. 7.5.1 Private Private accessibility means that members within a class can only be accessed by that class. 7.5.2 Protected Protected accessibility means that members within a class can be accessed by member functions declared by that class and any classes "inherited" from that class. 7.5.3 Public Public accessibility means that members within a class can be accessed by any part of a program. bpbonline all rights reserved Part I Classes and Objects 159 7.6 CLASS DECLARATION The class keyword defines a class where all data members are private by default, unless we spe- cifically change them using the public or protected keywords. For example, the following program segment declares cursor of class type point. class point /* class declaration */ { int x; /* Private by default */ int y; } point cursor; /* cursor of class point */ Note that cursor is an object of the class point. 7.6.1 Data Members The internal data of a class is called data member (or member data). The data members in a class are by default private unless otherwise declared public. By private we mean that the data members can only be accessed by the member functions declared within the class. Exa mp le 1 A class date is defined below as day, month and year. class date { private: int day; int month; int year; }; class date thisday; The program using this definition of date is shown in Figure 7.1(a). The program uses its internal data for displaying the date. The output of the program is shown in Figure 7.1(b). The variable thisday is an object of the date class. You will observe that the data members, namely day, month, and year are declared as public in the class date definition. It is in this way only, that the data members can be accessed by the pro- gram outside the class. If the data members are declared as private, then the output will not be displayed as shown in Figure 7.1(b). Rather, the compiler will give an error message. You may like to test it by replacing the keyword public with private. 7.6.2 Member Functions The definition of a class may also contain functions (called member functions) that operate on data members defined within the class. bpbonline all rights reserved 160 Programming in C++ Part I /* Program to demonstrate the declaration of class */ /* defining data members */ #include <iostream.h> void main (void) { class date { public: int day; int month; int year; ); class date thisday; thisday.day = 12; thisday.month = 5; thisday.year = 1997; cout << "\n This days date is = "<< thisday.day <<endl; cout << "\n This days month is = " << thisday.month << endl; cout << "\n This days year is = " << thisday.year << endl; } Figure 7.1(a) Program assigning data to the data members of a class Figure 7.1(b) Typical run of the program given in Fig- ure 7.1 (a) The syntax for class declaration containing private and public data members and function members is: class user_defined_name { private: data_type members function members public: data_type members function members }; class user_defined_name variable1, variable2,..,variablen;
This days date is = 12
This days month is = 5
This days year is = 1997
bpbonline all rights reserved Part I Classes and Objects 161 7.6.3 Private and Public Members All the data members in the declaration of the class are private. But you can change the accessi- bility of data members within a class by using the keywords public and protected as follows: class point /* Example class declaration */ { private: int x; /* private by default */ public: int y; /* y is now declared public */ } point cursor; /* cursor of class point */ Read the following sub-program. class uv { private: int func1; public: int func1(); }; In the above declaration of the class uv, C++ compiler will give error because the data member int func1 and the function member int func1() bear the same name. C++ compiler assumes by default that all data members in a class are private. If you want to make them public, then you need to use the keyword public. A single name can denote several function members provided their types are sufficiently different. The same name cannot denote both a member function and a data member. 7.6.4 Default Labels A class binds the data and its associated functions together. It allows the data (and the functions if so desired) to be hidden, from external use or manipulation. By defining a class, we create a new abstract (symbolic) data type that can be treated like any other built-in data type such as float or int. Class is a key concept of C++. A class is a user defined type and is the unit of data hiding and encapsulation. A class provides a unit of modularity. bpbonline all rights reserved 162 Programming in C++ Part I The class declaration describes the type and scope of its members. The member function defi- nitions of a class describe how the class functions are implemented. The class body contains the declaration of variables and functions. These functions and variables are collectively called members. These are grouped under two sections, namely private and public. The keywords private and public are known as visibility labels. The members that have been declared as private can be accessed only from within the class by the member functions. On the other hand, public members can be accessed from outside the class as well. The keyword typedef is not required since a class name itself is a type of name. The key- words private, public and protected are used to specify the three levels of access protec- tion for hiding data and function members internal to the class. The keywords private and public, known as labels describe the accessibility of the class member (data and function members). Any program using a particular class can access the public members directly. But in a program, the private members can only be accessed by using the function members within the class. 7.6.5 Data Hiding and Encapsulation In C++, the class construct allows you to declare data and functions, as public, private and pro- tected type. The implementation details of a class can be hidden from the user. This is done by the data hiding principle. The internal data (the member data) of a class are by default private. It means that they are separated from the outside world. Thus, putting data members and functions which operate on data members (also called encapsulation) groups all the pieces of an object into one neat package. In this manner, the data members are protected from the intentional misuse of important data. Encapsulation prevents the change of data members from the class. Diffe re nc e b e twe e n C la ss a nd Struc ture The difference between a structure and class lies in the validity of area of the members. In a class, by default, all members are private while in a structure they are public. A class declaration specifies the representation of data members of the class and the set of operations that can be applied to such members using member functions. A class provides a template, defines the member functions and variables that are required for objects of the class type. bpbonline all rights reserved Part I Classes and Objects 163 7.6.6 Arrays within a Class A class definition can also contain data of the type array as shown in the following class of Ban- kAcct for data member account_holder[20]. class BankAccount { private: int account_number; char account_holder[20]; float current_balance; public: int getAccountNumber(); char* getAccountHolder(); float getCurrentBalance(); }; /* end of class definition */ In the above program segment, the data member account_holder is of the type array of size 20. 7.7 CLASS FUNCTION DEFINITION Class functions declared within the class operate on the data members of the class. You may define a member function within the class declaration or declare it inside the class (like a function prototype) and define it outside the class. 7.7.1 Member Function Definition inside the Class Declaration A function declared as a member of a class is called a member function. Such functions are nor- mally declared as public in the class declaration unless otherwise specified. The member functions operate upon three data types and accordingly are classified as: (a) Manager Functions (b) Accessor Functions (c) Implementor Functions M a na g e r Func tions The manager functions are used to initialize and clean up the class objects. Constructors and destructors are the two examples of member functions that carry out the manager functions. Ac c e ssor Func tions The accessor member functions are the constructor functions that return information about an objects current state. bpbonline all rights reserved 164 Programming in C++ Part I Imp le me ntor Func tions The implementor functions modify the data members and are also called asmutators. A class contains a data member and function which are also called methods. The func- tions must be defined before they are used. 7.7.2 Member Functions Functions that are declared as per certain rules. These rules are discussed in the subsection below. M e mb e r Func tion De c la ra tion in a C la ss You can declare a member function in two ways: In the first method, it is defined on the member function within the class declaration. To define the function within a class, simply add the function directly to the class. For example the function position() in the following program segment is added within the class point definition. This method works for only short functions. class point /* Example class declaration */ { private: int x; /* Private by default */ int y; public: int position() { return X; } The second method of function declaration works for long functions. In this method, we declare a function inside the class (like a function prototype) and define it outside the class as given in the program segment shown in Figure 7.2. class point /* Example class declaration */ { private: int x; /* Private by default */ int y; int position() /* prototype declared within class */ } int point::position()/*function position() belongs to class point*/ { return x } Figure 7.2 A member function defined outside the class bpbonline all rights reserved Part I Classes and Objects 165 In Figure 7.2, the function position is declared as prototype within the class point. The defini- tion of the function position() is outside the class. In the statement: int point :: position() the scope operator :: identifies that the function position() belongs to the class point. Thus, the scope operator (::) identifies the class to which the function belongs to. The scope access operator(::) lets you access a global variable even if a local variable uses the same name. Local variables can only be accessed within the function that declares them. Global variables can be accessed by any function in a program. Only the scope operator (::) identifies the function as a member of a particular class. Without the scope operator, the function definition would create an ordinary function, subject to the usual rules of access and scope of a function. Class members can be one of the following member lists: (a) data (b) functions (c) classes The keyword class must be used while defining a class. By default the data members of a class are private unless declared as public. Thus by default, data members are accessible to the functions defined within the class but not to the outside world. M e mb e r Func tion De finition outsid e the C la ss De c la ra tion A member function can also be defined outside the class declaration. For example, the program segment given in Figure 7.3 defines a function outside the class declaration. The member func- tions are defined separately as part of the program: class simple { private: int x; int y; public: int sum() /* member function declaration */ }; /* end of class declaration */ int simple :: sum() /* member function definition */ { return (x + y); } Figure 7.3 Member function defined outside the class declaration bpbonline all rights reserved 166 Programming in C++ Part I In the program given in Figure 7.3, the function sum() is only shown as a prototype within the class and defined outside the class. It belongs to the class simple and this identification has been possible because of the scope access operator (::). If we had not used this operator then the defini- tion of sum() would have been like any other function definition. A class declaration specifies the representation of objects of the class and the set of oper- ations that can be applied to such objects. Class objects may be assigned, passed as argu- ments to functions or returned by functions. To call a class function, you need to specify the function plus the name of the class the function works with by using the dot operator. For example, to use the sum function you need to type the following: simple.sum(); 7.7.3 Scope Resolution Operator(::) The scope resolution operator(::) let us access a global variable even if a local variable uses the same name. The syntax requires the placement of the double colon, ::, immediately in front of the globally referenced identifier. The program shown in Figure 7.4(a) declares a global and local variable with the same name "sybil". Local variables can only be accessed within the function that declares them. Global vari- ables can be accessed by any function in a program. You use the :: scope access operator to over- ride a local variable name. The output is shown in Figure 7.4(b). /* Program demonstrating use of scope operator(::) */ #include <iostream.h> int sybil; void main() { void subfunction(); sybil = 2; /* prints the value of 2 */ cout << "\n This is global variable = " << sybil << "\n"; subfunction(); } void subfunction() { int sybil; sybil = 1; ::sybil++; /* increments the global variable sybil */ /* Prints the value of 1 */ (Contd...) bpbonline all rights reserved Part I Classes and Objects 167 cout << "\n This is the local variable = " << sybil << "\n"; /* Prints the value of 3 */ cout << "\n This is the global variable = " << ::sybil; } Figure 7.4(a) Using scope operator for differentiating between global and local variables Figure 7.4(b) Output of the program given in Figure 7.4(a) Note that you need to use the scope resolution operator(::) along with the class name in the header of the function definition. Then only the scope operator identifies the function as a member of a particular class. Without the use of scope operator, the function definition would create an ordinary function, subject to the usual function rules of access and scope. The program segment shown in Figure 7.5 illustrates how a member function is declared within the class declaration but functions are defined separately as part of the program. The scope operator (::) helps the compiler identify as to which class it belongs to. The function sum() belongs to the class simple. Similarly, the function diff() belongs to class sample. The use of scope operator (::) is important for defining the member functions outside the class declaration. /* Program using scope operator (::) for defining */ /* the member functions outside the class declaration */ #include <iostream.h> class simple { private: int x; int y; public: int sum(); /* member function declaration */ int diff(); /* member function declaration */ }; /* end of class definition */ int simple :: sum() /* member function definition */ { return (x+y); } int simple :: diff() /* member function definition */ { return (x-y); } Figure 7.5 Using scope operator for defining the member functions outside the class declaration This is global variable = 2
This is the local variable = 1
This is the gloabal variable = 3
bpbonline all rights reserved 168 Programming in C++ Part I 7.7.4 Private and Public Member Functions A member function (declared as a member of a class) is mostly given the attribute of public because it may be called outside the class either in a program or in another function. However, if a function is given the attribute as private, then it cannot be called by the program outside the class. But it can be called by the function declared within the class. Also, it can operate on data declared within the class. The program shown in Figure 7.6(a) declares the following member functions as public: void get_data(); void display(); float sum(); float diff(); Each of these functions belongs to the class simple_math. These may be used in the program outside the class declaration as shown in the program given in Figure 7.6(a). /* Program demonstrating the use of arithmetic operations */ /* using member function and displaying contents on the screen */ #include <iostream.h> class simple_math { private: float x; float y; public: void get_data(); void display(); float sum(); float diff(); }; /* end of class definition */ simple_math object1; /* object1 is of the type simple_math */ void simple_math :: get_data() { cout << "\n Enter two numbers " << endl; cin >> x >> y; } void simple_math :: display() { cout << "x =" << x << endl; cout << "y =" << y << endl; cout << " sum of x and y = " << sum() << endl; cout << " difference of x and y = " << diff()<< endl; } (Contd...) bpbonline all rights reserved Part I Classes and Objects 169 float simple_math :: sum() { return ( x + y); } float simple_math :: diff() { return (x - y); } void main (void) { object1.get_data(); object1.display(); object1.sum(); object1.diff(); } Figure 7.6(a) Using scope operator for defining the member functions outside the class declaration Figure 7.6(b) Output of the program given in Figure 7.6(a) The member function of a class can be called only by the variables defined to be of that class using a dot operator. For example, in the program shown in Figure 7.6(a), object1 is the variable declared to be of the class type simple_math. The functions get_data(), display(), sum() and diff() are invoked using the dot (.) operator in the main() block statements of the program. 7.7.5 Nesting of Member Functions As described in Section 7.7.4, the member function of a class can be called only by the variables defined to be of that class using a dot operator. However there is an exception to this rule. A member function can be called by using its name inside another member function of the same class. This is known as nesting of member functions. The program shown in Figure 7.7(a) illus- trates the method of calling function largest() in the function show(). The output is shown in Fig- ure 7.7(b). 7.8 CREATING OBJECTS As explained in Section 7.4, a class is a definition from which objects can be created. A class brings together data and all the functions which may act on member data into a single unit.
Enter two numbers 45 56 x =45 y =56 sum of x and y = 101 difference of x and y = -11
bpbonline all rights reserved 170 Programming in C++ Part I /* Program demonstrating nesting of member functions */ #include <iostream.h> class nest_func { private: int x; int y; public: void get_data(); /* member function declaration */ void show (); /* member function declaration */ int largest (); /* member function declaration */ }; /* end of class definition */ int nest_func :: largest() { if (x >= y) return (x); else return (y); } void nest_func :: get_data() { cout << "\n input values of x and y" << endl; cin >> x >> y; } void nest_func :: show() { cout << "\ largest value = " << largest() << endl; } main() { nest_func A; A.get_data(); A.show(); } Figure 7.7(a) Using nesting of member functions Figure 7.7(b) Output of the program given in Fig- ure 7.7 (a) We shall try to understand the idea of an object in C++ by a simple example. Let us consider a function that gives us the square root of a value, which we might declare as:
input values of x and y 4 9 largest value = 9 bpbonline all rights reserved Part I Classes and Objects 171 float square_root(); The above function works out square roots. It is recognized by the name "Square_root" and returns a value in the form of a floating point number. We can use it in the following assignment statement: x = square_root(y); The above statement in C++ has the effect of calling the function "square_root" and passing it the value of the variable "y". The function works out the square root of that value and passes it back as a floating point number. That value is then assigned to "x". The points to note here are: (a) The function can be used exactly as shown above, that is, the function is used directly within a statement in the program as if it were a variable. (b) All functions within C++ have a data type which determines the form of the return value. For example, in the case of square_root it is of the floating point type. A class is a user defined data type, while an object is an instance or example of a class tem- plate. An object is an entity that can store data and send and receive messages. The data type of a function in C++ is similar to the "class" of an object, because the "class" of an object defines the data type and the structure or shape that an object can have. An object when executed returns a value. The class defines the type of data returned by an object. The general syntax for defining the object of a class is: class user_defined_name { private: data_type members list of functions public: data_type members list of functions } user_defined_name object1, object2, object...n; Where object1, object2,..., objectn are the identical classes of user_defined_name. Two more examples of declaring classes and object are given below: Exa mp le 2 The program segment shown in Figure 7.8 illustrates how to declare and to create objects of class hospital_info. bpbonline all rights reserved 172 Programming in C++ Part I /* Program segment creating Hospital_info object */ #include <iostream.h> class hospital_info { private: char p_nameint[30]; int age; char sex; char p_address[50]; int p_ward_no; int p_bed_no; public: void get_data(); /* member function declaration */ void show (); /* member function declaration */ void payment();/* member function declaration */ }; /* end of class definition */ hospital_info obj1,obj2; /* obj1, obj2 declared as objects */ /* of the class hospital_info */ Figure 7.8 Objects of class hospital_info Exa mp le 3 The program segment shown in Figure 7.9 illustrates how to declare and to create objects of class emp (for employee). /* Program creating objects of class employees */ #include <iostream.h> class emp { private: int number; int age; public: void get_data() { cout << "number = "; cin >> number; cout << "age = "; cin >> age; } (Contd...) bpbonline all rights reserved Part I Classes and Objects 173 void display_data() { cout << "\n number = " << number << endl; cout << " age = " << age << endl; } }; /* end of class emp definition */ emp x,y; /* x and y are the two objects of class emp */ Figure 7.9 Objects of class emp 7.8.1 Differences between Objects and Functions The main difference between objects and functions is that a function is usually written to perform only a single task such as the calculation of a square root. A class offers a range of different ser- vices, each of which is activated by a different message. The function that an object carries out is thus determined by the message that is sent to it. As an example, the class "number" could offer addition, subtraction, multiplication, division and exponentiation as the tasks it can perform. Each task would be invoked by a different message which would include a number as a parameter. Thus "number +1" would have the meaning: add 1 to the current value of number. "+1" is the message which is sent to the object "number", The "+" invokes the service of addition. Note that "1" is also an object which has value "1"; it is an instance or an example of the class "number". Thus for each class all the services that can be provided are defined once and for all. They are coded into the class and are never coded elsewhere. This is applied to any service which you may wish to provide on any organized data, no matter how complex it is. It could be printing or reading a record. It could also be searching a value in a table or arranging a table in a particular order. The two other parts defined in a class are: (a) Messages (b) Methods M e ssa g e s These are valid messages to which an object will respond. They are the labels for the method. Suppose a guest comes to my house and I tell my wife to get two cups of tea. The message I have given is clear and precise and is a valid message. My wife will get two cups of tea. The method to prepare the tea is none of my concern, because she may either prepare tea herself or order the ser- vant to do so, or she may bring the tea which was already prepared. I am only concerned with the final action. The action is to bring two cups of tea. Another point to be noted in an object oriented programming is that the same message may be executed differently by different objects. For example, if my father alone was present in the house, and if I had told him to get two cups of tea, he might not have taken any action at all. Thus the message though clear is not valid for the object (i.e. for my father). However, the same message would have been valid for my mother, because she would have gladly brought the tea if my wife was not at home. bpbonline all rights reserved 174 Programming in C++ Part I In object-oriented programming, the procedure of an action is hidden from the person passing the message. The same message is executed differently by different objects. Thus we may conclude that an action is initiated in objected-oriented programming by the transmission of a message to an agent (object) responsible for that action. The message encodes the request for an action, and is accompanied by an additional piece of information (arguments), needed to carry out the request. The receiver is the agent to whom the message is sent. If the receiver accepts the message, it accepts the responsibility to carry out the indicated action. In response to a message, the receiver will perform some method to satisfy the request. M e thod s This is the processing which is carried out when a message is sent to an object. A method is defined for each message. The data type of a function in C++ is similar to the "class" of an object, because the "class" of an object defines the data type and the structure or shape that an object can have. 7.8.2 Accessing Class Data Members A data member of a class construct is accessed using the . (period) operator. For example, the data_member of the class_object is accessed by writing class_object.data_member The program in Example 4 demonstrates the access of the data members, namely day, month and the year of the class date. Exa mp le 4 The program shown in Figure 7.10(a) demonstrates how to use data member and member function of a class. The output of this program is shown in Figure 7.10(b). /* Program to demonstrate access of data members of class date*/ #include <iostream.h> class date { private: Contd. bpbonline all rights reserved Part I Classes and Objects 175 int day; int month; int year; public: void get_date_data(int dd, int mm, int yy) { day = dd; month = mm; year = yy; } void display (void) { cout << "\n This days date is = " << day << endl; cout << "\n This days month is = " << month << endl; cout << "\n This days year is = " << year << endl; } }; /* end of class declaration */ void main (void) { date thisday; int dd,mm,yy; dd =12; mm = 5; yy = 1997; thisday.get_date_data(dd,mm,yy); thisday.display(); } Figure 7.10(a) Program demonstrating access of data members of a class Figure 7.10(b) Typical run of the program given in Fig- ure 7.10(a) 7.8.3 Accessing Member Functions A function member of a class construct is accessed using the . (dot) operator. Program segment shown in Figure 7.11 demonstrates the access of member functions.
This days date is = 12
This days month is = 5
This days year is = 1997
bpbonline all rights reserved 176 Programming in C++ Part I /* Program segment demonstrating access of class member function */ #include <iostream.h> class simple { private: int x; int y; public: int sum(); int diff(); }; /* end of class simple definition */ void main (void) { simple one; one.sum(); /* accessing the member function sum() */ one.diff(); /* accessing the member function diff() */ } Figure 7.11 Program demonstrating access of class member functions Exa mp le 5 The program shown in Figure 7.12(a) demonstrates reading data variables of a class by the mem- ber function and accessing the member function for displaying output on the screen by the dot operator (.). The output of this program is shown in Figure 7.12(b). /* Program demonstrating reading data variables of a class */ /* by the member function and accessing member function */ */ for displaying output on the screen */ #include <iostream.h> class date { private: int day; int month; int year; public: void get_date_data(void) { cout << "Enter the date (dd-mm-yy) " << endl; cin >> day >> month >> year; } void display (void) (Contd...) bpbonline all rights reserved Part I Classes and Objects 177 { cout << "\n This days date is = " << day << endl; cout << "\n This days month is = " << month << endl; cout << "\n This days year is = " << year << endl; } }; /* end of class declaration */ void main (void) { date thisday; thisday.get_date_data(); /* accessing member function */ thisday.display(); /* accessing member function */ } } Figure 7.12(a) Program demonstrating reading data variables of a class by the member function and displaying contents on the screen Figure 7.12(b) Typical run of the program given in Fig- ure 7.12(a) Exa mp le 6 The program shown in Figure 7.13(a) demonstrates the bank customer object. // This C++ program uses the C++ class keyword // to create a fully formed bank customer object #include <string.h> #include <iostream.h> #define NAME_LENGTH_PLUS_NULL 66 class bank_object (Contd...) Enter the date (dd-mm-yy) 12 5 1997
This days date is = 12
This days month is = 5
This days year is = 1997
bpbonline all rights reserved 178 Programming in C++ Part I { char customer_name[ NAME_LENGTH_PLUS_NULL ]; double customer_balance; unsigned int customer_PIN; unsigned int PIN ( void ); double Balance ( void ); public: void BeginAccount ( char *init_name, double init_balance, unsigned int init_PIN ); void Deposit ( double amount ); void Withdraw ( double amount ); void PrintCustomer ( void ); void PrivateAcctInfo( unsigned int_PIN ); } A_Customer; void bank_object::BeginAccount( char *init_name, double init_balance, unsigned int init_PIN ) { strcpy(customer_name,init_name); customer_balance = init_balance; customer_PIN = init_PIN; } void bank_object::Deposit( double amount ) { customer_balance += amount; } void bank_object::Withdraw( double amount ) { customer_balance -= amount; } void bank_object::PrintCustomer( void ) { cout << "\nWelcome to AutoTeller: " << customer_name; } double bank_object::Balance( void ) { return( customer_balance); } unsigned int bank_object::PIN( void ) { return( customer_PIN); } (Contd...) bpbonline all rights reserved Part I Classes and Objects 179 void bank_object::PrivateAcctInfo( unsigned suspect_PIN ) { char UserSelection; if( suspect_PIN == customer_PIN ) { cout << "\nPlease enter P for PIN number \n" << "B for Balance: "; cin >> UserSelection; if( UserSelection == P ) cout << "\n Your secret PIN number is: " << A_Customer.PIN( ); else { cout << "\n Your current balance is: "; cout.setf(ios::fixed); cout.precision(2); cout << A_Customer.Balance ( ); } } else cout << "Invalid PIN number."; } void main( void ) { unsigned int suspect_PIN; A_Customer.BeginAccount ( "RAMESH",35123.56,44128 ); cout << "Please enter your current PIN number: "; cin >> suspect_PIN; A_Customer.PrivateAcctInfo( suspect_PIN ); A_Customer.PrintCustomer( ); A_Customer.PrivateAcctInfo( suspect_PIN ); A_Customer.Withdraw( 532.78 ); A_Customer.PrivateAcctInfo( suspect_PIN ); A_Customer.Deposit( 1235.46 ); A_Customer.PrivateAcctInfo( suspect_PIN ); } Figure 7.13(a) Program uses the C++ class keyword to create a bank customer object Figure 7.13(b) Typical run of the program given in Fig- ure 7.13(a) The main() block begins by declaring a new local variable, suspect_PIN, which it uses to hold a legal PIN number entered by the user. After sending A_Customer a message to initialize Welcome to AutoTeller: RAMESH Please enter P for PIN number B for Balance: b
Your current balance is: 35123.56 Please enter P for PIN number B for Balance: p
bpbonline all rights reserved 180 Programming in C++ Part I itself, the program invokes the function A_Customer.PrivateAcctInfo(). Since the member func- tion is public, this is a legal member function access. The body of PrivateAcctInfo() takes in the responsibility of validating the suspect_PIN and, if correct, asks the user which type of sensitive output they would like, namely PIN information or account balance. You should note that the code of A_Customers private data has member functions, PIN() and Balance(), which in turn have direct access to A_Customers private data members, custom- er_PIN and customer_balance. Exa mp le 7 The program shown in Figure 7.14(a) demonstrates the solution of a quadratic equation using object-oriented programming techniques (OOP in short). The coefficients a, b and c are read from the keyboard. The results are shown depending upon the value of the discriminator defined as sqrt(b^2 - 4*a*c). As used, if the value of the discriminator is zero, then the roots are equal. If the discriminator is negative, then the roots are imaginary, otherwise the two roots are calculated. The results are shown in Figures 7.14(b) and 7.14(c). /* Program demonstrating the use of object-oriented programming */ /* method for solving the quadratic equation a*x^2 + b*x + c = 0 */ #include <iostream.h> #include <math.h> class quad { private: float a; float b; float c; public: void get_data(float a, float b, float c); void display(); void root_equal(float a, float b); void root_imag(); void root_real(float a, float b, float det); }; /* end of class definition */ void quad :: get_data(float a1, float b1, float c1) { a = a1; b = b1; c = c1; } (Contd...) bpbonline all rights reserved Part I Classes and Objects 181 void quad :: display() { cout << "Coefficient a = " << a << endl; cout << "Coefficient b = " << b << endl; cout << "Coefficient c = " << c << endl; } void quad :: root_equal(float a, float b) { float x; x = -b/(2*a); cout << " The two equal roots are = " << x << endl; } void quad :: root_imag() { cout << "\n roots are imaginary " << endl; } void quad :: root_real(float a, float b, float det) { float x1,x2,temp; temp = sqrt(det); x1 = (-b + temp) / (2 * a); x2 = (-b - temp) / (2 * a); cout << "\n The two real roots are \n" ; cout << "root1 = " << x1 << endl; cout << "root2 = " << x2 << endl; } void main (void) { quad equ; float a1, b1, c1; cout << "\n Enter coefficient a b c" << endl; cin >> a1 >> b1 >> c1; equ.get_data(a1 , b1, c1); equ.display(); if (a1 == 0) { float t; t = - c1/b1; cout << "Only one root and its value = " << t << endl; } else { float det; (Contd...) bpbonline all rights reserved 182 Programming in C++ Part I det = b1 * b1 - 4 * a1 * c1; if (det == 0) equ.root_equal(a1,b1); else if (det < 0 ) equ.root_imag(); else equ.root_real(a1, b1, det); } }/* End of Main() */ Figure 7.14(a) Program demonstrating the use of object-oriented programming method for solving the quadratic equation a*x^2 + b*x + c = 0 Figure 7.14(b) Typical run of the program given in Fig- ure 7.14(a)
Enter coefficient a b c 0 2 2 Coefficient a = 0 Coefficient b = 2 Coefficient c = 2 Only one root and its value = -1
Enter coefficient a b c 1 1 1 Coefficient a = 1 Coefficient b = 1 Coefficient c = 1
roots are imaginary
Figure 7.14(c) Typical run of the program given in Fig- ure 7.14(a)
Enter coefficient a b c 1 2 1 Coefficient a = 1 Coefficient b = 2 Coefficient c = 1 The two equal roots are = -1
Enter coefficient a b c 2 5 2 Coefficient a = 2 Coefficient b = 5 Coefficient c = 2
The two real roots are root1 = -0.5 root2 = -2
bpbonline all rights reserved Part I Classes and Objects 183 7.8.4 Arrays of Objects As already described in earlier chapters, an array is a user defined data type whose members are of the same data type and all the data members are stored in adjacent memory locations. For design- ing a large size of database, use of arrays is very essential. General syntax of the array of structures is as follows: class user_defined_name { private: data_type members function members public: data_type members function members }; class user_defined_name object[MAX] In the above definition, MAX defines the size of the array of class object. The following pro- gram segment declares an array of class object. const int MAX = 100; class emp { private: int number; int age; char sex; public: void get_data() { cout << "number: "; cin >> number: }; class emp obj[MAX]; Here obj is an array of class emp of the size MAX. Exa mp le 8 The program shown in Figure 7.15(a) reads employee data from the keyboard and shows the con- tents of the class on the screen. The class emp is defined as an array of class objects. This program creates an array of class objects and accesses data members and member functions. The output is shown in Figure 7.15(b). bpbonline all rights reserved 184 Programming in C++ Part I /* Program creating array of class emp */ /* and accessing data as well as function members */ #include <iostream.h> const int MAX = 50; class emp { private: int number; int age; public: void get_data() { cout << "number = "; cin >> number; cout << "age = "; cin >> age; } void display_data() { cout << "\n number = " << number << endl; cout << " age = " << age << endl; } }; /* end of class emp definition */ void main() { emp object[MAX]; /* Array of class object */ int i,n; cout << "\n How many employees " << endl; cin >> n; cout << "Enter data for each employee " << endl; for (i = 0; i <= n-1; ++i) { int j = i; cout << endl; cout << " employee record = " << j + 1 << endl; object[i].get_data(); } cout << " \n Display of Employees Data \n" ; for ( i = 0; i <= n-1; ++i ) { object[i].display_data(); } } /* End of Program */ Figure 7.15(a) Program creating an array of class emp and accessing data as well as function members bpbonline all rights reserved Part I Classes and Objects 185 Figure 7.15(b) Typical run of the program given in Fig- ure 7.15(a) 7.9 OBJECTS AS FUNCTION ARGUMENTS An object may be used as a function argument just like any other data type. This can be done in one of the following two ways: (a) A copy of the entire object is passed to the function. (b) Only the address of the object is transferred to the function The method (a) is called pass-by-value. In this method, since a copy of the object is passed to the function, any change to the object inside the function, does not affect the object that is used to call the function. The method (b) is called pass-by-reference. When an address of the object is passed, the called function works directly on the actual object used in the call. It means that any changes made to the object inside the function will reflect in the value of the actual object. This method is more efficient, because it requires to pass only the address of the object and not the entire object and no extra memory is used for the copy of the original object. 7.9.1 Pass by Value The program shown in Figure 7.16(a) demonstrates the use of objects as function arguments. It performs the addition of time in the hours and minutes format. The member function sum() is invoked by the object T3, with the objects T1 and T2 as arguments. It can be accessed only by using the dot operator, namely T1.hrs and T1.mts. Thus, inside the function sum(), the variables hrs and mts refer to T3; T1.hrs and T1.mts refer to T1; and T2.hrs and T2.mts refer to T2. Figure 7.16(b) shows the run of the program in Figure 7.16(a). How many employees 2 Enter data for each employee
employee record = 1 number = 234 age = 45
employee record = 2 number = 345 age = 56
Display of Employees Data
number = 234 age = 45
number = 345 age = 56 bpbonline all rights reserved 186 Programming in C++ Part I /* Program demonstrating passing objects as function arguments */ #include <iostream.h> class time{ private: int hrs; int mts; public: void get_time(int h, int m) { hrs = h; mts = m; } void show_time (void) { cout << hrs << " hours and "; cout << mts << " minutes " << "\n"; } void sum (time,time);/* objects as arguments */ }; /* end of class definition */ void time :: sum(time t1, time t2) /* t1 and t2 are objects */ { mts = t1.mts + t2.mts; hrs = mts/60; mts = mts%60; hrs = hrs + t1.hrs + t2.hrs; } main () { time T1, T2, T3; T1.get_time(2,45); /* Time T1 entered */ T2.get_time(1,30); /* Time T2 entered */ T3.sum(T1,T2); /* Time T3 = T1+T2 */ cout << " T1 = " ; T1.show_time(); /* display time T1 */ cout << " T2 = " ; T2.show_time(); /* display time T2 */ cout << " T3 = " ; T3.show_time(); /* display time T3 */ } Figure 7.16(a) Programs demonstrating passing objects as function arguments bpbonline all rights reserved Part I Classes and Objects 187 Figure 7.16(b) Typical run of the program given in Fig- ure 7.16(a) Figure 7.17 illustrates how the members are accessed inside the function sum(). T1 = 2 hours and 45 minutes T2 = 1 hours and 30 minutes T3 = 4 hours and 15 minutes
Figure 7.17 Members of objects accessed within a called function Objects can be passed as arguments to a non member function. But, such functions can have access to the public member functions only through the objects passed as arguments to it. These functions cannot have access to the private data members. TEST PAPER Time: 3 Hrs Max Marks: 100 Answer the following questions. 1. What are classes and how do they differ from ordinary data structures like arrays or structures. 2. List the three levels of accessibility offered by classes. 3. What is an object and how can object be defined in C++. How does it differ from a class? 4. Differentiate between the data members and member functions. 5. What is a scope resolution operator? How is it useful for defining the data member and member function of a class? 6. Explain the difference between a data member of a class and the conventional variables in C++ 4 15 hrs mts (T1 + T2) 45 T1.mts T1.hrs 2 T2.mts T2.hrs 30 1 T3.sum(T1,T2) bpbonline all rights reserved 188 Programming in C++ Part I 7. Define a class to represent a bank account. Include the following members: Data Members (a) Name of the depositor (b) Type of the account (c) Account number (d) Balance amount in the account Member Functions (a) To deposit an amount (b) To withdraw an amount (c) To display name of the account holder, type of account and the balance Write the main() block to test the program. 8. Define a class to represent a school fee account. Include the following members: Data Members (a) Name of the student (b) Student roll number (c) Fee Month (d) Balance amount in the account Member Functions (a) To deposit amount of fee (b) To display name of the student, student roll number and the balance due Write the main() block to test the program. 9. Define a class to represent a pay roll account. Include the following members: Data Members (a) Employee name (b) Employee number (c) Designation (d) Date of joining the organization (e) Account number (d) Balance amount in the account Member Functions (a) To deposit salary for a month (b) Deductions if any (c) To display the name of the employee, the employee number, account number and the balance. Write the main() block to test the program. 10. Develop an object oriented program in C++ to create a library information system con- taining the following for all books in the library: bpbonline all rights reserved Part I Classes and Objects 189 Data Members (a) Access number (b) Name of the author (c) Title of the book (d) Publishers name (e) Price of the book (d) Number of copies Member Functions (a) To add any new book to the list of books in the library, (b) To delete a book from the library (c) To display names of the books, authors name and the price of each book. Write the main() block to test the program. bpbonline all rights reserved
Test Bank For Accounting Information Systems Understanding Business Processes 4th Edition by Brett Considine Alison Parkes Karin Olesen Yvette Blount Derek Speer 9780730302476