Class Object

38
3.1 INTRODUCTION Strostrup when he developed this language named it as “C with classes”. From this we easily interpret that the concept of classes is the most important concept of this language. Classes can be considered as an extension of the concept of “Structures” which we studied with “C++” language. A structure in “C++” is a collection of similar or dissimilar types of data grouped together as a single unit. C++ extends the reach of structures by allowing the inclusion of even functions within structures. The functions defined within a structure have a special relationship with the data elements present within the structure. Placing data and functions together into a single entity is the central idea of Object-Oriented-Programming. 3.2 CLASSES A class basically binds a group of objects together. A class provides common information of a group of objects. Classes are the fundamental building blocks in object-oriented programming. Each class represents some kind of entity in the real Objectives of the Chapter 3 CLASSES AND OBJECTS In this chapter, we will learn Representation of data in computer. Figure 3.1 Class contain data and function Definition CLASS : A class is a collection of objects that have the identical properties, common behavoir, and shared relation ship. A class binds the data and its related functions together

description

class

Transcript of Class Object

  • 1CLASSES AND OBJECTS

    3.1 INTRODUCTION

    Strostrup when he developed this language named it asC with classes. From this we easily interpret that the conceptof classes is the most important concept of this language. Classescan be considered as an extension of the concept of Structureswhich we studied with C++ language. A structure in C++ isa collection of similar or dissimilar types of data grouped togetheras a single unit. C++ extends the reach of structures by allowingthe inclusion of even functions within structures. The functionsdefined within a structure have a special relationship with thedata elements present within the structure. Placing data andfunctions together into a single entity is the central idea ofObject-Oriented-Programming.

    3.2 CLASSES

    A class basically binds a group ofobjects together. A class provides commoninformation of a group of objects. Classesare the fundamental building blocks inobject-oriented programming. Each classrepresents some kind of entity in the real

    Objectives of the Chapter

    3 CLASSES AND OBJECTS

    In this chapter, we will learn

    Representation of data in computer.

    Figure 3.1Class contain data

    and function

    DefinitionCLASS : A class is a collection of objectsthat have the identical properties,common behavoir, and shared relationship. A class binds the data and its relatedfunctions together

  • 2 CLASSES AND OBJECTS

    world system. A class provides a method for describing an entity and the functionsassociated with it (Encapsulation).

    For example there may be thousands of types of vehicles. Each vehicle isbuilt from the same set of basic components and has the same functions. In object-oriented terms, we say that object(say bicycle, motorcycle, car, bus, aeroplane,helicopter and ship) is an instance or example of the class known as vehicles. A classis the blueprint or template from which individual objects are created.

    Figure 3.2 Classes and their members

    A class is a method of organizing the data and functions in the same structure.The classes are syntatically an extension of structures. The basic difference betweena structure and a class is that the structure has only public members but classes havethe provision of categorizing the members into private, protected and public.

    The aim of the C++ class concept is to provide the programmer with a tool forcreating new types that can be used as conventionally as the built-in types. A class isa user defined type. We design a new type (class) to provide definition of a concept thathas no direct counterpart among the built-in types. The fundamental idea in defining anew type is to separate the details of the implementation (data abstraction) from theproperties essential to the correct use of it. Such a separation is best expressed bychanneling all uses of the data structure and internal housekeeping routines througha specific interface.

    3.3 NEED FOR CLASSES AND OBJECTS

    Programs are usually written to solve real-world problems, such as keeping trackof Student records, Employee records or simulating the working of a Car system.Object-Oriented Programming (OOP) is a style of programming that focuses onusingclasses and objectsto design and build application softwares. A Class can bethought of as a description of an object and an object can be thought of as a model of theconcepts, processes, or things in the real world that are meaningful to your applicationsoftware.

    For example, in a Pre-UniversityAutomation software, you would have aCollege object, Student object, Teacherobject, and a Library object among others.These objects would work together (and withmany other objects) to provide thefunctionality that you want your applicationsoftware to have.

    { }class vehicle

    {class computer

    }

  • 3CLASSES AND OBJECTS

    Object-Oriented-Programming is used to develop many such applications bothsimple and complex applications, business applications and games, mobile and desktopapplications. Developers choose to program in the object-oriented paradigm becausethe proper use of classes and objects makes it easier to build, maintain, and upgradean application. Also, developing an application with classes and objects that have beentested increases the reliability of the application.

    3.4 DECLARATION OF A CLASS

    A class definition is a process ofnaming a class, variables and functionsof the class. The variables declaredinside a class are known as datamembers. Similarly, functions are declared inside a class are known as member functions.

    A class declaration specifies the representation of objects of the class and theset of operations that can be applied to such objects.

    The general syntax of the class declaration is:

    class Class-Name{

    private :// private data and functions

    protected :// protected data and functions

    public :// public data and functions

    };The class is a keyword. The declaration of a class is enclosed within the curly

    brackets and terminated with a semicolon(Note, data constructs such as structure andclasses end with a semicolon). The declaration of a class requires us to understand theuse of the following attributes.

    1. Class-Name: The name of a class works like the type specifier for the class.Using the name of the class we will have to create all the objects associatedwith it, similar to the way variables are created using the data types.

    2. Access Specifiers: They help in controlling the access of the data members.Different access specifiers such as private, protected and public can beused. The keywords private, protected and public are used to specifiy thethree levels of access protection for hiding data and function members internalto the class.a) private: The class members (data and functions) written under this

    section are accessible by class member functions or friend functions.The data members or member functions declared private cannot beaccessed from outside the class. The objects of the class can access theprivate members only through the public member functions of theclass. This property is also called information hiding. By default classmembers in a class are private.

    DefinitionCLASS MEMBER : A component of a class. Classmembers may be either data or functions.

  • 4 CLASSES AND OBJECTS

    ICU DOCTO

    RABC HO

    SPITALprivateprotected public

    Reception

    Access Specifiers

    b) protected: The class members of this section are accessible by thefunction members of same class and friend functions or friend classes aswell as by functions of derived classes. For all other operations protectedmembers are similar to private members.

    c) public:The class members declared in this section are accessible frominside or outside the class. Some of the public functions of a classprovide interface for accessing the private and protected membersof the class. For example, initialization of a class object with private orprotected data is always carried through public functions.

    In this chapter we discuss about private and public access specifiers indetail. The protected access specifier will be discussed in chapter 5.

    The following Figure 3.4 illustrates the concept of private, protected andpublic members of a class.

    Figure 3.4 A physical illustration of private, protected and publicmembers of a class

    3. Data Members: They are used to describe the properties (characteristics orattributes) of the object under consideration. For example,i. Date class may have data members such as Day, Month and Year.ii. Student class may have data members such as RegNo, Name, DOB and

    Marks.iii. Reactangle class may have data members such as length and breadth.iv. Employee class may have data members such as EmpNo, Name, DOB,

    DOJ and Salary.

    4. Member Functions: They are used to describe the operations that can beperformed with the data members of the class. For example,i. Date class may have member functions such as InputDate(),

    DisplayDate(), and so on.ii. Student class may have member functions such as ReadInfo(),

    DisplayInfo(), Result(), and so on.iii. Reactangle class may have member functions such as InputData(),

    CalculateArea(), DisplayInfo(), and so on.iv. Employee class may have member functions such as ReadEmpInfo(),

    IncomeTax(), Deduction(), NetSalary(), and so on.

  • 5CLASSES AND OBJECTS

    Keyword Name of class

    Brackets

    Keyword private and colon

    Keyword public and colonSemicolon

    Example 3.1: Suppose that we want to define a class to implement the date of a day ina program.

    Let us call this class Date which might give us the Date of birth of a student orthe Date of joining the college. To represent date in the computers memory, we usethree int variables, one to represent the day, one to represent the month, and one torepresent the year.

    Suppose these three variables are:int day;int month;int year;

    We also want to perform the following operations on the time:1. Input the date2. Display the date

    To implement these two operations, we will write two functions InputDate(),and DisplayDate(). From this discussion, it is clear that the class Date has 5 members,three member variables and two member functions. Some members of the class Date willbe private while the others will be public. Deciding which member to make publicand which to make private depends on the nature of the member. The general rule isthat any member that needs to be accessed outside of the class is declared public andany member that should not be accessed directly by the user should be declared private.

    The following statements declare the class Date:

    class Date{

    private:int day;int month;int year;

    public:void InputDate();void DisplayDate();

    };

    Figure 3.5 Syntax of a class definitionIn this declaration:

    The class Date has three data members day,month and year and two memberfunctions InputDate() and DisplayDate().

    The three member variables day,month and year are private to the class andcannot be accessed outside of the class.

    The two member functions InputDate() and DisplayDate() can directly accessthe member variables (day,month and year). In other words, when we write the

    private data

    public data

  • 6 CLASSES AND OBJECTS

    definitions of these functions, we do not pass these member variables asparameters to the member functions.

    The two member functions InputDate()and DisplayDate() are public tothe class and can be accessed outside the class.

    The member function InputDate() is created to input values for the date andthe function DisplayDate() is used to display the contents of the data members.

    Example 3.2: The following declaration illustrates the specifications of a class calledStudent. The properties of a Studentclass such as RegNo, Name, Combination, Address,Sex and Marks can be grouped as:

    class Student{

    private : long RegNo;char Name[30];char Combination[5];char Address[50];int Sex;int Marks;

    public :void GetInfo();void DisplayInfo();void Result();

    }; // end of class definition

    Example 3.3: The following declaration illustrates the specifications of a class calledRectangle.

    class Rectangle{

    private:float length;float breadth;float area;

    public:void InputData();void CalculateArea();void DisplayInfo();

    }; // end of class definition

    The following declaration is identical while accessing the member of a class.Declaration 1 Declaration 2

    class Date class Date{ { private: int day;

    int day; int month;int month; int year;int year; .........

    ...................... };};The members in a class without any access specifier are private by default.Hence, the use of private keyword is optional in Declaration 2.

    NOTE

  • 7CLASSES AND OBJECTS

    3.5 MEMBER FUNCTIONSThe next step after the class declaration is to define the member functions.

    Member functions are functions that are included within in a class (member functionsare also called Methods). The member functions identified with the class can then beexpanded either inside the class declaration or outside the class declaration. Memberfunctions can be defined in two places:

    1. Inside the class declaration2. Outside the class declaration

    3.5.1 INSIDE THE CLASS DECLARATION

    Let us consider the class Date in which InputDate() and DisplayDate() aremember functions. These functions can be defined inside the class as described below.

    class Date{

    private :int day,month,year;

    public :void InputDate( ) // member function{

    cout > day >> month >> year;

    }void DisplayDate() // member function{

    cout

  • 8 CLASSES AND OBJECTS

    void CalculateArea() // member function{

    area = length * breadth;}void DisplayInfo() // member function{

    cout

  • 9CLASSES AND OBJECTS

    Example 3.5: Consider the class Rectangle in which InputData(), CalculateArea()and DisplayInfo() are member functions. These functions can be defined outsidethe class as described below.

    class Rectangle{

    private:float length, breadth, area;

    public :void InputData(); // member function declarationvoid CalculateArea() // member function declarationvoid DisplayInfo() // member function declaration

    }; // end of class definition

    void Rectangle::InputData() // member function definition{

    cout > length;cout > breadth;

    }void Rectangle::CalculateArea() // member function definition{

    area = length * breadth;}void Rectangle::DisplayInfo() // member function definition{

    cout

  • 1 0 CLASSES AND OBJECTS

    KeywordName of the user defined class

    Name of the userdefined objects

    class ClassName Object_Name1, Object_Name2,;

    Figure 3.6 Syntax for creating objects

    Example 3.5 : Consider the following object declaration

    class Date Today, NextDate, DOB;OR

    Date Today, NextDate, DOB;

    Above statement creates three objects, Today, NextDate and DOB for the classDate. It is important for us to remember that the definition of the class Date does notcreate any objects. It only describes how they will look when they are created, just as astructure definition describes how a structure will look but does not create any structurevariables. It is objects when created that participate in program operations.

    Defining an object is similar to defining a variable of any data type. Objects canalso be created by placing their names immediately after the closing bracket.

    Example 3.6 : Consider the following class and object declaration:

    class Date{

    ......

    ......} Today, NextDate, DOB

    creates objects Today, NextDate and DOB and of the class Date.

    Example 3.7 : The following program segment shows how to declare and create of objects.class Student{

    private : long RegNo;char Name[30];char Combination[5];char Address[50];int Sex;int Marks;

    public :void GetInfo();void DisplayInfo();void Result();

    }; // end of class definitionStudent S1,S2,S3; // creation of objects

    creates objects S1,S2 and S3 for the class Student and reserve space for S1,S2 and S3.

  • 1 1CLASSES AND OBJECTS

    When an object is created space is set aside for it in memory. Defining objectsin this way means creating them. This is also called instantiating them. The terminstantiating arises because an instance of the class is created. An object is an instance(that is, a specific example) of a class. Objects are sometimes called instance variables.

    3.7 ACCESSING CLASS MEMBERS

    Once the required number of objects is created we are now ready to access itsmembers. This is achieved by using the member access operator, dot(.). The syntax foraccessing members (data and functions) of a class is shown in Figure 3.7.

    ObjectName . DataMember;

    (a) Syntax for accessing a data member of a class

    ObjectName . MemberFunctionName( Actual Arguments );

    (b) Syntax for accessing a member function of a class

    Figure 3.7 Syntax for accessing class members

    Example 3.8: Consider the following statements:

    Today.day = 16;Today.month = 8;Today.year = 2013;

    In the above program segment values have been assigned to respective datamembers of the object Today. Note that the above statements are valid only when allthe data members are defined under public access specifier.

    Example 3.9: Consider the following statements:

    Today.InputDate();Today.DisplayDate();

    These statements do not look like normal function calls. Here we are callingand executing the member functions of the class Date through the corresponding objects.Thus we have this strange syntax of calling functions. Because InputDate(), and

    Name of the userdefined object Data member of a class

    member access specifier

    Name of the userdefined object

    member access specifier

    Name of themember function

    arguments to the function

  • 1 2 CLASSES AND OBJECTS

    DisplayDate()are member functions of the Date class and these functions shouldalways be operated through an object of this class.

    The first call Today.InputDate()allows us to enter a date in the form dd/mm/yy to the object Today. The second call Today.DisplayDate() allows us to display theentered date through the object Today.

    The member functions cannot be called directly by itself. For example, thefunction call

    InputDate();

    is invalid because a member function is always called to act on a specific object and noton the class in general. Attempting to access the member function directly would belike trying to drive the blueprint of a car. Not only does this statement make no sense,but the compiler will also issue an error message if you attempt it. Member functionsof a class can be accessed only by an object of that class.

    Program 3.1: A program to assign values to the data members of a class Date anddisplay the result on the screen in the proper format.

    #include class Date{ public :

    int day,month,year;}; // end of class definition/* Main function */void main(){

    Date Today; // Create an object Today of class Date

    Today.day = 16; // Assign values to data members to TodayToday.month = 8;Today.year =2013;cout

  • 1 3CLASSES AND OBJECTS

    #include class Date{ private :

    int day,month,year; // data members are private}; // end of class definitionvoid main(){

    Date Today; // Create an object Today of class Date

    Today.day = 16; // Assign values to data members to TodayToday.month = 8;Today.year =2013;cout

  • 1 4 CLASSES AND OBJECTS

    accessing the data members ofobject Today from the memberfunctions.

    The Area()and Perimeter() aremember functions called inside theDisplayInfo() function to calculatethe area and perimeter of the rectanglebefore the value is displayed. This isknown as nesting of member functions.

    NOTE

    /* Main function */void main(){

    Date Today; // object creationToday.InputDate();Today.DisplayDate();

    } OUTPUT Enter a Date as DD mm yy : 12 30 2013

    Entered date is 12/30/2013

    Program 3.3: A C++ program to find the area and perimeter of a Rectangle usingObject-Oriented programming technique.

    #include class Rectangle{

    private :float length,breadth;

    public :void InputValues() // member function{

    cout > length;cout > breadth;

    }int Area() // member function{

    return( length * breadth );}int Perimeter() // member function{

    return( 2*(length + breadth) );}// Nesting of member fucntion Area() and Perimeter()void DisplayInfo() // member function{

    cout

  • 1 5CLASSES AND OBJECTS

    OUTPUT Input the length of the rectangle : 4Input the breadth of the rectangle : 5Length of the rectangle is : 4Breadth of the rectangle is: 5Area of the rectangle is : 20Perimeter of the rectangle is : 18

    Program 3.4: A C++ program to illustrate the use of simple arithmetic operations such asaddition, subtraction, multiplication and division using member functions. These memberfunctions are defined out of the scope of a class definition.

    #include class Arithmetic{ private:

    int x,y; public : void InputData();

    int Add();int Subtract();int Multiply();float Divide();void DisplayInfo();

    }; // end of class definition

    void Arithmetic::InputData() // function definition{ cout > x >> y;}int Arithmetic::Add() // function definition{

    return (x+y);}int Arithmetic::Subtract() // function definition{

    return (x-y);}int Arithmetic::Multiply() // function definition{

    return (x*y);}float Arithmetic::Divide() // function definition{

    return ((float)x/y);}void Arithmetic::DisplayInfo() // function definition{

    cout

  • 1 6 CLASSES AND OBJECTS

    Calling member functions in themain program and returnint and float values respectively.

    /* Main function */void main(){

    Arithmetic ArObject; // creation of Arithmetic object

    ArObject.InputData();ArObject.DisplayInfo();

    cout

  • 1 7CLASSES AND OBJECTS

    float CompoundInterest() // member function definition{

    float amount = principal * pow(1+rate/100,time);return (amount - principal);

    }void DisplayInfo() // member function definition{

    cout

  • 1 8 CLASSES AND OBJECTS

    void DisplayMax() // member function definition{

    cout

  • 1 9CLASSES AND OBJECTS

    /* Main function */void main(){

    Book MyBook;MyBook.TotalPages(525);MyBook.SetPage(152);cout

  • 2 0 CLASSES AND OBJECTS

    int Series::EvenSum() // member function definition{

    for(i=2,sum=0;i

  • 2 1CLASSES AND OBJECTS

    Program 3.9: A C++ program to read and write N numbers into one dimensional array

    using object oriented programming technique.

    #include #include class OneDimArray{

    private :int a[100],m;

    public :void SetNoOfElements(int n) // member function definition{

    m=n;}void ReadArray(); // member function declarationvoid DisplayArray(); // member function declaration

    };void OneDimArray::ReadArray() // member function definition{

    cout

  • 2 2 CLASSES AND OBJECTS

    Program 3.9: A C++ program to read N numbers into one dimensional array. Find the

    maximum, minimum and average of N numbers using object oriented programming technique.

    #include #include class OneDimArray{ private :

    int a[100],m; public : void SetDimension(int n)

    {m=n;

    }void ReadArray();void DisplayInfo();int FindMax();int FindMin();float FindAverage();

    };void OneDimArray::ReadArray(){

    cout

  • 2 3CLASSES AND OBJECTS

    /* Main function */void main(){

    int n; // number of elementsOneDimArray A;cout > n;A.SetDimension(n);A.ReadArray();A.DisplayInfo();

    }OUTPUT Input number of elements : 6

    Enter 6 array elements5 6 -7 8 -2 13Array elements are :5 6 -7 8 -2 13Maximum number = 13Minimum number = -7Average of 6 numbers = 3.83333

    The array variable a[] is a private member of the class OneDimArray. Themember function FindMin() returns the maximum of the array a[]. Similarly, themember function FindMin() returns minimum of the array a[] and the member functionFindAverage()finds the average on N numbers. All these member functions are nestedin the DisplayInfo() member function of the class OneDimArray.

    We can also include character array as a class member data. The followingprogram shows how a character array can used as a class member data.

    Program 3.10: Develop an object-oriented program in C++ to read the followinginformation from the keyboard.

    Register numberName of the studentcombinationMarksAddress

    Display the result on the screen using a member function DisplayStdInfo().#include class Student{

    private :long RegNo;char Name[20];char Comb[6];int Marks;char Address[40];

    public :void ReadStdInfo() // member function definition{

    cout > RegNo;cout > Name;cout > Comb;cout > Marks;cout > Address;

    }

    Declared three arrays ofcharacter as data memebers ofa class

  • 2 4 CLASSES AND OBJECTS

    void DisplayStdInfo() // member function definition{ cout

  • 2 5CLASSES AND OBJECTS

    void Matrix::MatrixRead() // member function definition{

    cout

  • 2 6 CLASSES AND OBJECTS

    public:void ReadData();int TotalRuns();void ShowData();void ShowName();

    }; // end of class definitionvoid CricketData::ReadData(){

    cout Name;cout

  • 2 7CLASSES AND OBJECTS

    switch(choice){ case 1: Player.ShowData();

    break; case 2: Player.ShowName();

    break; case 3: cout

  • 2 8 CLASSES AND OBJECTS

    3.9 CLASSES, OBJECTS AND MEMORY

    Objects are the identifiers declared for class elements. Object is a compositionof one more variable declared in the class. Each object has its own copy of public andprivate data members. An object can access to its own copy of data members andhave no access to data members of other objects.

    We have stated that the class declaration does not allocate memory to the classdata member. When an object is declared, memory is reserved for only data membersand not for member functions. The following program illustrates this concept.

    Program 3.13: A C++ program to display the size of the objects and a class.

    #include class Student{

    private :long RegNo; // 4 bytes of memorychar Name[20]; // 20 bytes of memorychar Comb[6]; // 6 bytes of memoryint Marks; // 2 bytes of memorychar Address[40]; // 40 bytes of memory

    public :void ReadStdInfo();void DisplayStdInfo();

    }; // end of class definitionvoid main(){

    Student S1,S2; // Total 72 bytes for S1 and 72 bytes for S2cout

  • 2 9CLASSES AND OBJECTS

    Figure 3. 8 Data members and member functions in memory

    3.10 ARRAY OF CLASS OBJECTS

    An array is a collection of similar data and stored in contiguous memory locations.An array can be of any type including user-defined type created using struct, classand typedef. We can also create an array of objects. The declaration of an array ofclass objects is similar to the declaration of the array of structures in C++.

    Example 3.10: Consider the following class declaration:class Student{

    private :long IdNo;char Name[20];int Marks;

    public :void ReadData();void DisplayData();

    }; // end of class definition

    Student PUC[5];

    The class Student has been declared as an object of size 5.

  • 3 0 CLASSES AND OBJECTS

    Figure 3. 9 Array of objects

    Example 3.11 : The Student is a user defined type and can be used to declare an array ofobjects Student of different categories. For example, consider the following declarations:

    Student PUC[5]; Contains 5 objects of type Student class.Student DEGREE[100]; Contains 100 objects of type Student class.Student COLLEGE[1500]; Contains 1500 objects of type Student class.

    As shown in Figure 3.9, arrays of object of type Student are created. The arrayPUC[5] contains IdNo, Name and Marks information for five objects. Similarly, theDEGREE contains 100 objects (Degree students) and the COLLEGE contains 1500 objects(College students).

    Program 3.14: Write a program to create a database for a college containing IdNo, Nameand Marks.#include #include #include class Student{ private :

    int IdNo; char Name[20]; int Marks;

    public : void ReadData( ) {

    cout Name;cout > Marks;

    } void DisplayData( ) {

    cout

  • 3 1CLASSES AND OBJECTS

    for(i=0;i

  • 3 2 CLASSES AND OBJECTS

    float Employee::ComputeNetSalary(){

    return (BasicSalary+HRA+DA);}void Employee::ReadEmpInfo(){

    cout EmpCode;cout EmpName;cout Design;cout BasicSalary;cout HRA;cout DA;

    }void Employee::DisplayInfo(){

    cout

  • 3 3CLASSES AND OBJECTS

    Enter the employee code:101Enter the employee name:VinayEnter designation:ManagerEnter the basic salary:15000Enter HRA:1600Enter DA:1000

    Enter the employee code:102Enter the employee name:MadhuEnter designation:AttenderEnter the basic salary:5000Enter HRA:1000Enter DA:500------------------------------------------------Code Name Desig Salary------------------------------------------------100 Varun CEO 277000101 Vinay Manager 17600102 Madhu Attender 6500------------------------------------------------

    In the above program the member function ComputeNetSalary() is defined underprivate section of the class Employee. This private member function has the strictaccess control. Only the member functions of the same class can access this memberfunction. The private members of the class are inaccessible outside the class (in themain() function). Hence, the ComputeNetSalary() is nested in DisplayInfo()function.

    3.11 PASSING OBJECTS AS ARGUMENTS (TO FUNCTION)

    Objects can be passed to functions as arguments in just the same way as anyother type of data is passed. Simply declare the functions parameter as a class typeand use an object of that class as an argument when calling the function. As with othertypes of data, by default all objects are passed by value to a function. The Program 3.16demonstrates how objects can be used as functions arguments.

    Program 3.16: Define a class called Exam which has the following members:Private Data members:

    Physics marks,Chemistry marks andMaths marks

    Public Member functions:

    i. Function ReadMarks() to read an object Exam which contains marks ofPhysics, Chemistry and Maths subjects.

    ii. Function DisplayInfo() to display the details of an object.iii. Function Total() to find the total marks of PUC and CET examinations in

    each subject.

    #include #include

  • 3 4 CLASSES AND OBJECTS

    class Exam // class definition{

    private :float Physics,Chemistry,Maths;

    public :void ReadMarks(){

    cout Physics;cout Chemistry;cout Maths;

    }void DisplayInfo(){

    cout

  • 3 5CLASSES AND OBJECTS

    In the above program, the class Exam declared with three member variables,Physics, Chemistry and Maths. The function ReadMarks()reads marks of PUC and CETobjects using the following statements:

    PUC.ReadMarks();CET.ReadMarks();

    In main() function, the statement

    PUCplusCET.Total(PUC, CET);

    calls the member function Total() of the class Exam by the object PUCplusCET, with theobject PUC and CET as arguments. This function directly access the Physics, Chemistryand Maths variables of PUCplusCET. The member of PUC and CET can be accessed only byusing the dot operator (like PU.Physics, CT.Physics) within the Total() member function.Figure 3.10 illustrates how the members are accessed inside the function Total().

    Figure 3. 10 Objects of the Exam class as arguments

    Program 3.17: Create a class called Time that contains seconds, minutes and hours.Use public functions called ReadTime() to read time, AddTime() to add two times andDisplayTime() to display time.

    #include #include class Time{

    private :int ss,mm,hh;

    public :void ReadTime(){

    cout > hh >> mm >> ss;

    }

  • 3 6 CLASSES AND OBJECTS

    void DisplayTime(){

    cout

  • 3 7CLASSES AND OBJECTS

    Program 3.18: Define a class called Exam which has the following members:Private Data members:

    Physics marks,Chemistry marks andMaths marks

    Public Member functions:

    i. Function ReadMarks() to read an object Exam which contains marks ofPhysics, Chemistry and Maths subjects.

    ii. Function DisplayInfo() to display the details of an object.iii. Function Total() to find the total marks of PUC and CET examinations in

    each subject.(Use member function return an object of the class)

    #include #include class Exam // class definition{

    private :float Physics,Chemistry,Maths;

    public :void ReadMarks(){

    cout Physics;cout Chemistry;cout Maths;

    }void DisplayInfo(){

    cout

  • 3 8 CLASSES AND OBJECTS

    PUC.ReadMarks(); // Read PUC markscout