c++lang chap7

Upload: samaan

Post on 03-Jun-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 C++Lang chap7

    1/33

    CHAPTER 7

    Classes and Objects

    7.1 INTRODUCTIONThe 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 calledclass. 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 aninstancein 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 ourexample 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

  • 8/11/2019 C++Lang chap7

    2/33

    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 usingconstructorsanddestructors. 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 asetof problems.

    7.4 OBJECTS DECLARED AS A CLASS

    In C++ programming, a class is adefinitionfrom 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

  • 8/11/2019 C++Lang chap7

    3/33

    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 classpoint.

    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 defaultprivateunless otherwise declared public. By private we mean that the data members

    can only be accessed by the member functions declared within the class.

    Ex a m p le 1

    A classdateis 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

    variablethisdayis an object of thedateclass.

    You will observe that the data members, namely day, month, and year are declared as public in

    the classdate 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 bedisplayed as shown in Figure 7.1(b). Rather, the compiler will give an error message. You may

    like to test it by replacing the keywordpublicwithprivate.

    7.6.2 Member Functions

    The definition of aclassmay also contain functions (called member functions) that operate on data

    members defined within the class.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap7

    4/33

    160 Programming in C++ Part I

    /* Program to demonstrate the declaration of class *//* defining data members */#include 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

  • 8/11/2019 C++Lang chap7

    5/33

    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 classuv, C++ compiler will give error because the data member

    int func1 and the function member int func1()bear the same name.

    C++ compiler assumesby defaultthat 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 namecannotdenote both a memberfunctionand adatamember.

    7.6.4 Default Labels

    A class binds the data and its associated functions together. It allows the data (and the functions ifso 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 asfloatorint.

    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

  • 8/11/2019 C++Lang chap7

    6/33

    162 Programming in C++ Part I

    Theclassdeclaration 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 keywordsprivate

    andpublicare known as visibilitylabels. 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 keywordtypedefis 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 thedata 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 theintentional misuse of important data.

    Encapsulation prevents the change of data members from the class.

    Diffe re nc e be 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

  • 8/11/2019 C++Lang chap7

    7/33

    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 ge r Funct ions

    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

  • 8/11/2019 C++Lang chap7

    8/33

    164 Programming in C++ Part I

    Imp le m e ntor Func t ions

    The implementor functions modify the data members and are also calledasmutators.

    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 m be r Funct ion De c la ra tion i n 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

  • 8/11/2019 C++Lang chap7

    9/33

    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 functionposition()is outside the class. In the statement:

    int point :: position()

    the scope operator :: identifies that the functionposition() 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. Withoutthe 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 keywordclassmust 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 m b e r Func tion De finit ion ou tsid 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

  • 8/11/2019 C++Lang chap7

    10/33

    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 classsimple and this identification has been

    possible because of the scope access operator (::). If we had not used this operator then the defini-

    tion ofsum()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 thesum 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 int sybil; void main() { void subfunction(); sybil = 2; /* prints the value of 2 */ cout

  • 8/11/2019 C++Lang chap7

    11/33

    Part I Classes and Objects 167

    cout

  • 8/11/2019 C++Lang chap7

    12/33

    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 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 x >> y;}

    void simple_math :: display() { cout

  • 8/11/2019 C++Lang chap7

    13/33

    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 asnesting of member functions. The program shown in Figure 7.7(a) illus-

    trates the method of calling functionlargest()in the functionshow(). 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

  • 8/11/2019 C++Lang chap7

    14/33

    170 Programming in C++ Part I

    /* Program demonstrating nesting of member functions */#include 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 x >> y; }

    void nest_func :: show() { cout

  • 8/11/2019 C++Lang chap7

    15/33

    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 ofsquare_rootit 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 memberslist of functions

    public:data_type memberslist 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:

    Ex a m p le 2

    The program segment shown in Figure 7.8 illustrates how to declare and to create objectsof class

    hospital_info.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap7

    16/33

    172 Programming in C++ Part I

    /* Program segment creating Hospital_info object */#include 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

    Ex a m p le 3

    The program segment shown in Figure 7.9 illustrates how to declare and to create objectsof class

    emp(for employee).

    /* Program creating objects of class employees */

    #include

    class emp

    {

    private:

    int number;

    int age;

    public:

    void get_data()

    {

    cout > number;

    cout > age;

    }

    (Contd...)

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap7

    17/33

    Part I Classes and Objects 173

    void display_data() {

    cout

  • 8/11/2019 C++Lang chap7

    18/33

    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 amessage 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 somemethodto satisfy the request.

    M e t h o d 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_memberof theclass_objectis 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.

    Ex a m p 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 class date { private:

    Contd.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap7

    19/33

    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

  • 8/11/2019 C++Lang chap7

    20/33

    176 Programming in C++ Part I

    /* Program segment demonstrating access of class member function */#include 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

    Ex a m p 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 class date{ private: int day; int month; int year; public:

    void get_date_data(void) { cout day >> month >> year; } void display (void)

    (Contd...)

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap7

    21/33

    Part I Classes and Objects 177

    { cout

  • 8/11/2019 C++Lang chap7

    22/33

    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

  • 8/11/2019 C++Lang chap7

    23/33

    Part I Classes and Objects 179

    void bank_object::PrivateAcctInfo( unsigned suspect_PIN ){ char UserSelection; if( suspect_PIN == customer_PIN ) { cout UserSelection; if( UserSelection == P ) cout

  • 8/11/2019 C++Lang chap7

    24/33

    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.

    Ex a m p le 7

    The program shown in Figure 7.14(a) demonstrates the solution of a quadratic equation usingobject-oriented programming techniques (OOP in short). The coefficientsa,bandcare 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 #include 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

  • 8/11/2019 C++Lang chap7

    25/33

    Part I Classes and Objects 181

    void quad :: display() { cout

  • 8/11/2019 C++Lang chap7

    26/33

    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(); elseequ.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 = 1Coefficient 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 c2 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

  • 8/11/2019 C++Lang chap7

    27/33

    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 membersfunction members

    public:data_type membersfunction 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:

    };class emp obj[MAX];

    Hereobjis an array of class emp of the size MAX.Ex a m p 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 classempis 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

  • 8/11/2019 C++Lang chap7

    28/33

    184 Programming in C++ Part I

    /* Program creating array of class emp *//* and accessing data as well as function members */#include const int MAX = 50; class emp { private: int number; int age; public: void get_data()

    {cout > number;cout > age;

    } void display_data() {

    cout

  • 8/11/2019 C++Lang chap7

    29/33

    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 calledpass-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 calledpass-by-reference. When an address of the object is passed, the called

    function worksdirectlyon 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 byusing 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 = 234age = 45

    number = 345

    age = 56

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap7

    30/33

    186 Programming in C++ Part I

    /* Program demonstrating passing objects as function arguments */

    #include

    class time{

    private:

    int hrs;

    int mts;

    public:

    void get_time(int h, int m)

    {

    hrs = h;

    mts = m;

    }

    void show_time (void)

    {

    cout

  • 8/11/2019 C++Lang chap7

    31/33

    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 ofobjects

    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 argumentsto 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.hrs2

    T2.mts

    T2.hrs

    30

    1

    T3.sum(T1,T2)

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap7

    32/33

  • 8/11/2019 C++Lang chap7

    33/33

    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.