0% found this document useful (0 votes)
124 views38 pages

Classes and Objects: in This Chapter, We Will Learn

1. The document discusses classes and objects in C++. It defines a class as a collection of objects that have identical properties, common behavior, and shared relationships. A class binds data and functions together. 2. A class provides a template or blueprint for creating individual objects. It encapsulates both data and functions that operate on that data. Classes allow programmers to create new user-defined types with their own properties and behaviors. 3. The document provides an example class definition for a Date class that contains private data members for the day, month, and year. It also contains public member functions to input and display a date. This demonstrates how classes organize related data and functions.

Uploaded by

hkgrao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
124 views38 pages

Classes and Objects: in This Chapter, We Will Learn

1. The document discusses classes and objects in C++. It defines a class as a collection of objects that have identical properties, common behavior, and shared relationships. A class binds data and functions together. 2. A class provides a template or blueprint for creating individual objects. It encapsulates both data and functions that operate on that data. Classes allow programmers to create new user-defined types with their own properties and behaviors. 3. The document provides an example class definition for a Date class that contains private data members for the day, month, and year. It also contains public member functions to input and display a date. This demonstrates how classes organize related data and functions.

Uploaded by

hkgrao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 38

1

CLASSES AND OBJECTS


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 i denti cal properti es,
common behavoir, and shared relation
ship. A class binds the data and its related
functions together
2 CLASSES AND OBJECTS
world system. A class provides a method for describing an entity and the functions
associated with it (Encapsulation).
For example there may be thousands of types of vehicles. Each vehicle is
built 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 class
is 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 between
a structure and a class is that the structure has only public members but classes have
the 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 for
creating new types that can be used as conventionally as the built-in types. A class is
a user defined type. We design a new type (class) to provide definition of a concept that
has no direct counterpart among the built-in types. The fundamental idea in defining a
new type is to separate the details of the implementation (data abstraction) from the
properties essential to the correct use of it. Such a separation is best expressed by
channeling all uses of the data structure and internal housekeeping routines through
a specific interface.
3.3 NEED FOR CLASSES AND OBJECTS
Programs are usually written to solve real-world problems, such as keeping track
of Student records, Employee records or simulating the working of a Car system.
Object-Oriented Programming (OOP) is a style of programming that focuses on
usingclasses and objectsto design and build application softwares. A Class can be
thought of as a description of an object and an object can be thought of as a model of the
concepts, processes, or things in the real world that are meaningful to your application
software.
For example, in a Pre-University
Automation software, you would have a
College object, Student object, Teacher
object, and a Library object among others.
These objects would work together (and with
many other objects) to provi de the
functionality that you want your application
software to have.
{ }
class vehicle
{
class computer
}
3
CLASSES AND OBJECTS
Object-Oriented-Programming is used to develop many such applications both
simple and complex applications, business applications and games, mobile and desktop
applications. Developers choose to program in the object-oriented paradigm because
the proper use of classes and objects makes it easier to build, maintain, and upgrade
an application. Also, developing an application with classes and objects that have been
tested increases the reliability of the application.
3.4 DECLARATION OF A CLASS
A class definition is a process of
naming a class, variables and functions
of the class. The variables declared
inside a class are known as data
members. Similarly, functions are declared inside a class are known as member functions.
A class declaration specifies the representation of objects of the class and the
set 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 and
classes end with a semicolon). The declaration of a class requires us to understand the
use 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 associated
with 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 be
used. The keywords private, protected and public are used to specifiy the
three levels of access protection for hiding data and function members internal
to 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 be
accessed from outside the class. The objects of the class can access the
private members only through the public member functions of the
class. This property is also called information hiding. By default class
members in a class are private.
Definition
CLASS MEMBER : A component of a class. Class
members may be either data or functions.
4 CLASSES AND OBJECTS
I
C
U
D
O
C
T
O
R
A
BC
H
O
SPITA
L
private protected
public
Reception
Access Specifiers
b) protected: The class members of this section are accessible by the
function members of same class and friend functions or friend classes as
well as by functions of derived classes. For all other operations protected
members are similar to private members.
c) public:The class members declared in this section are accessible from
inside or outside the class. Some of the public functions of a class
provide interface for accessing the private and protected members
of the class. For example, initialization of a class object with private or
protected data is always carried through public functions.
In this chapter we discuss about private and public access specifiers in
detail. The protected access specifier will be discussed in chapter 5.
The following Figure 3.4 illustrates the concept of private, protected and
public members of a class.
Figure 3.4 A physical illustration of private, protected and public
members of a class
3. Data Members: They are used to describe the properties (characteristics or
attributes) 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 be
performed 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.
5
CLASSES AND OBJECTS
Keyword
Name of class
Brackets
Keyword private and colon
Keyword public and colon
Semicolon
Example 3.1: Suppose that we want to define a class to implement the date of a day in
a program.
Let us call this class Date which might give us the Date of birth of a student or
the Date of joining the college. To represent date in the computers memory, we use
three int variables, one to represent the day, one to represent the month, and one to
represent 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 date
2. 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 will
be private while the others will be public. Deciding which member to make public
and which to make private depends on the nature of the member. The general rule is
that any member that needs to be accessed outside of the class is declared public and
any 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 definition
In this declaration:
The class Date has three data members day,month and year and two member
functions InputDate() and DisplayDate().
The three member variables day,month and year are private to the class and
cannot be accessed outside of the class.
The two member functions InputDate() and DisplayDate() can directly access
the 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 as
parameters to the member functions.
The two member functions InputDate()and DisplayDate() are public to
the class and can be accessed outside the class.
The member function InputDate() is created to input values for the date and
the function DisplayDate() is used to display the contents of the data members.
Example 3.2: The following declaration illustrates the specifications of a class called
Student. 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 called
Rectangle.
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

7
CLASSES AND OBJECTS
3.5 MEMBER FUNCTIONS
The next step after the class declaration is to define the member functions.
Member functions are functions that are included within in a class (member functions
are also called Methods). The member functions identified with the class can then be
expanded either inside the class declaration or outside the class declaration. Member
functions can be defined in two places:
1. Inside the class declaration
2. Outside the class declaration
3.5.1 INSIDE THE CLASS DECLARATION
Let us consider the class Date in which InputDate() and DisplayDate() are
member 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 << Input a Date as dd mm yy :;
cin >> day >> month >> year;
}
void DisplayDate() // member function
{
cout << Entered Date is :<<endl;
cout<< day <</<< month << / << year;
}
}; // end of class definition
The member functions InputDate() and DisplayDate() are defined quite
normally within the class declaration. These member functions perform common
operations such as setting data member values and reterving data stored in the class.
Example 3.4: Consider the class Rectangle in which InputData(), CalculateArea()
and DisplayInfo() are member functions. These functions can be defined inside
the class as described below.
class Rectangle
{
private:
float length, breadth, area;
public :
void InputData() // member function
{
cout << Input the length of the rectangle :;
cin >> length;
cout << Input the breadth of the rectangle :;
cin >> breadth;
}
8 CLASSES AND OBJECTS
void CalculateArea() // member function
{
area = length * breadth;
}
void DisplayInfo() // member function
{
cout<<Length of the rectangle is :<<length<<endl;
cout<<Breadth of the rectangle is:<<breadth<<endl;
cout<<Area of the rectangle is :<< area<endl;
}
}; // end of class definition
3.5.2 OUTSIDE THE CLASS DEFINITION
To define a member function outside the class declaration, you must link the
class name of the class with the name of the member function. We can do this by
preceding the function name with the class name followed by two colons (::). The two
colons(::) are called scope resolution operator.
The general form of a member function defined outside the class is
return-type Class-Name :: Member-Function-Name( parameter list )
{
Function-Body;
}
The member functions in the Date class can be defined outside the class as
described below.
class Date
{
private :
int day,month,year;
public :
void InputDate( ); // member function declaration
void DisplayDate(); // member function declaration
}; // end of class definition
void Date:: InputDate( ) // member function definition
{
cout << Input a Date as dd mm yy :;
cin >> day >> month >> year;
}
void Date:: DisplayDate() // member function definition
{
cout << Entered Date is :<<endl;
cout<< day <</<< month << / << year;
}
Only the scope resol ution operator
identifies the function as a member of a
particular class (here Date). Wi thout
this scope resol uti on operator, the
function will be treated as an ordinary
functi on.
9
CLASSES AND OBJECTS
Example 3.5: Consider the class Rectangle in which InputData(), CalculateArea()
and DisplayInfo() are member functions. These functions can be defined outside
the class as described below.
class Rectangle
{
private:
float length, breadth, area;
public :
void InputData(); // member function declaration
void CalculateArea() // member function declaration
void DisplayInfo() // member function declaration
}; // end of class definition
void Rectangle::InputData() // member function definition
{
cout << Input the length of the rectangle :;
cin >> length;
cout << Input the breadth of the rectangle :;
cin >> breadth;
}
void Rectangle::CalculateArea() // member function definition
{
area = length * breadth;
}
void Rectangle::DisplayInfo() // member function definition
{
cout<<Length of the rectangle is :<< length<<endl;
cout<<Breadth of the rectangle is:<< breadth<<endl;
cout<<Area of the rectangle is :<< area <<endl;
}
3.6 CREATING OBJECTS
A class declaration only builds the
structure of an object. It just tells the complier
what an object is, what data it contains, and
what it can do. The class declaration does not
create any object.
An object is a very important concept
in OOP. All operations related to a class are
done with the help of the object. Thus it is necessary for us to first create an object. An
object is normally defined in the main() program as the first statement in main(). The
syntax for defining objects of a class is shown in Figure 3.6. Note that the keyword
class is optional.
Member functions defined inside the class definition are created as
inline functions by default. Functions defined outside the class are not
normally inline.
NOTE

Definition
OBJECT : An object is a real world
element whi ch i s an i denti fi abl e
enti ty wi th some characteristics
(attributes) and behavior(functions).
1 0 CLASSES AND OBJECTS
Keyword
Name of the user defined class
Name of the user
defined 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 class
Date. It is important for us to remember that the definition of the class Date does not
create any objects. It only describes how they will look when they are created, just as a
structure definition describes how a structure will look but does not create any structure
variables. It is objects when created that participate in program operations.
Defining an object is similar to defining a variable of any data type. Objects can
also 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 definition
Student 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 1
CLASSES AND OBJECTS
When an object is created space is set aside for it in memory. Defining objects
in this way means creating them. This is also called instantiating them. The term
instantiating 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 its
members. This is achieved by using the member access operator, dot(.). The syntax for
accessing 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 data
members of the object Today. Note that the above statements are valid only when all
the 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 calling
and 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 user
defined object
Data member of a class
member access specifier
Name of the user
defined object
member access specifier
Name of the
member function
arguments to the function
1 2 CLASSES AND OBJECTS
DisplayDate()are member functions of the Date class and these functions should
always 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 the
entered date through the object Today.
The member functions cannot be called directly by itself. For example, the
function call
InputDate();
is invalid because a member function is always called to act on a specific object and not
on the class in general. Attempting to access the member function directly would be
like 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 functions
of 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 and
display the result on the screen in the proper format.
#include <iostream.h>
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 Today
Today.month = 8;
Today.year =2013;
cout << "Today is ";
cout << Today.day <<"/"<<Today.month<<"/"<<Today.year;
}
OUTPUT
Today is 16/8/2013
A key feature of object-oriented-programming is data hiding. Above program does
not support data hiding feature, because the data members (day, month and year)
which are declared under public section can be accessed directly from the main program.
The data hiding feature can be achieved by declaring all the data members under private
section. Private data or functions can only be accessed from within the class.
The following program segment demonstrates the accessibility of data members.
Here, all the data members are declared under private section and these data members
cannot be accessed directly from the main program.
1 3
CLASSES AND OBJECTS
#include <iostream.h>
class Date
{
private :
int day,month,year; // data members are private
}; // end of class definition
void main()
{
Date Today; // Create an object Today of class Date
Today.day = 16; // Assign values to data members to Today
Today.month = 8;
Today.year =2013;
cout << "Today is ";
cout << Today.day <<"/"<<Today.month<<"/"<<Today.year;
}
The following error message will be displayed during the compilation time.
Date::day is not accessible
Date::month is not accessible
Date::year is not accessible
From the above program, we noticed that the private data members are not
accessible by the object directly. To access the private data members of a class,
member functions of the same class are used. The member functions must be declared
in the public section. This is illustrated in the following program.
Program 3.2: A C++ program to accept Date from the user and diaplay date on the
screen using Object-Oriented programming technique.
#include <iostream.h>
class Date
{
private :
int day,month,year;
public :
void InputDate() // member function
{
cout << "Enter a Date as DD mm yy :";
cin >> day >> month >> year;
}
void DisplayDate() // member function
{
cout << "Entered date is ";
cout << day <<"/" << month << "/" << year;
}
}; // end of class definition
Direct
access is
Not allowed
1 4 CLASSES AND OBJECTS
accessing the data members of
object Today from the member
functions.
The Area()and Perimeter() are
member functions called inside the
DisplayInfo() function to calculate
the area and perimeter of the rectangle
before the value is displayed. This is
known as nesting of member functions.
NOTE

/* Main function */
void main()
{
Date Today; // object creation
Today.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 using
Object-Oriented programming technique.
#include <iostream.h>
class Rectangle
{
private :
float length,breadth;
public :
void InputValues() // member function
{
cout << "Input the length of the rectangle :";
cin >> length;
cout << "Input the breadth of the rectangle :";
cin >> 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 << "Length of the rectangle is :"<<length<<endl;
cout << "Breadth of the rectangle is:"<<breadth<<endl;
cout << "Area of the rectangle is :" << Area()<<endl<<endl;
cout << "Perimeter of the rectangle is :" << Perimeter()<<endl;
}
}; // end of class definition
/* Main function */
void main()
{
clrscr();
Rectangle R;
R.InputValues();
R.DisplayInfo();
}
1 5
CLASSES AND OBJECTS
OUTPUT Input the length of the rectangle : 4
Input the breadth of the rectangle : 5
Length of the rectangle is : 4
Breadth of the rectangle is: 5
Area of the rectangle is : 20
Perimeter of the rectangle is : 18
Program 3.4: A C++ program to illustrate the use of simple arithmetic operations such as
addition, subtraction, multiplication and division using member functions. These member
functions are defined out of the scope of a class definition.
#include <iostream.h>
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 << "Input two numbers :";
cin >> 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 << "X = " << x << endl;
cout << "Y = " << y << endl;
cout << "Sum of two numbers =" << Add() << endl;
cout << "Difference between two numbers ="<< Subtract()<<endl;
}
Member functions are defined out of
the scope of a class definition
1 6 CLASSES AND OBJECTS
Calling member functions in the
mai n program and return
int and float values respectively.
/* Main function */
void main()
{
Arithmetic ArObject; // creation of Arithmetic object
ArObject.InputData();
ArObject.DisplayInfo();
cout << "Product of two numbers =" << ArObject.Multiply() << endl;
cout << "Division of two numbers =" << ArObject.Divide() << endl;
}
OUTPUT Input two numbers : 6 4
X = 6
Y = 4
Sum of two numbers = 10
Difference between two numbers = 2
Product of two numbers = 24
Division of two numbers = 1.25
In the above program, the class Arithmetic has the member function
DisplayInfo() having the statements
cout << "Sum of two numbers ="<< Add() <<endl;
cout << "Difference between two numbers ="<< Subtract() <<endl;
The first statement calls (nested function) the member function Add() to
compute the sum of class data members x and y. Similarly, second statement calls(nested
function) the member function Subtract() to compute the difference between class
data members x and y.
The product of x and y is computed by calling the member function Multiply()
in the main program and it returns int data. Similarly, division is computed by calling
the member function Divide().
Program 3.5: A C++ program to calculate simple interest and compound interest using
object oriented programming technique.
#include <iostream.h>
#include <math.h> // for pow() function
class Interest // class definition
{
private :
float principal, time,rate; // data members
public :
void GetData() // member function definition
{
cout << "Input principal amount :" << principal;
cout << "Input number of years :" << time;
cout << "Input rate of interest :" << rate;
}
float SimpleInterest() // member function definition
{
return (principal * time * rate /100);
}
1 7
CLASSES AND OBJECTS
float CompoundInterest() // member function definition
{
float amount = principal * pow(1+rate/100,time);
return (amount - principal);
}
void DisplayInfo() // member function definition
{
cout << "Simple interest =" << SimpleInterest()<<endl;
cout << "Compound interest =" << CompoundInterest();
}
}; // end of class definition
/* Main function */
void main()
{
Interest SimpleAndCompound; // creation of object
SimpleAndCompound.GetData(); // call member function for p,t and r data
SimpleAndCompound.DisplayInfo(); // call member function to compute SI and CI
}
OUTPUT Input principal amount : 10000
Input number of years : 2
Input rate of interest : 12
Simple interest = 2400
Compound interest = 2544
In the preceding programs 3.2 to 3.5, data members were declared in the private
section of the class declaration. When a class is used, its declaration must be available.
Thus, only description of the class is given to the user. The internal details of the
class, which are not essential to the user are hidden. This concept is known as data
hiding or data encapsulation.
Program 3.6: A C++ program to find the largest of two numbers using object oriented
programming technique.
#include <iostream.h>
class NumberMax
{
private :
int num1,num2;
public :
void ReadData() // member function definition
{
cout << "Input the first number :"; cin >> num1;
cout << "Input the second number :"; cin >> num2;
}
int FindMax() // member function definition
{
if(num1 > num2)
return num1;
else
return num2;
}
1 8 CLASSES AND OBJECTS
void DisplayMax() // member function definition
{
cout << "Maximum =" << FindMax();
}
}; // end of class definition
/* Main function */
void main()
{
NumberMax N;
N.ReadData();
N.DisplayMax();
}
OUTPUT 1 Input the first number : 34
Input the second number : 89
Maximum = 89
OUTPUT 2 Input the first number : -4
Input the second number : -9
Maximum = -4
The class NumberMax has the member function DisplayMax() having the
statement
cout << "Maximum =" << FindMax();
It calls the member function FindMax()to compute the maximum of two numbers.
We can also assign values to the data members of a class by passing value
paramters to the member functions. This is illustrated in the following program.
Program 3.7: Create a class called Book that contains PageCount and CurrentPage of
a book. Use public functions called TotalPages() to read total pages of the book and set
the current page using the SetPage() function, Output the current page using the
GetCurrentPage() function.
#include <iostream.h>
class Book
{
private:
int PageCount; // data member of the class Book
int CurrentPage; // data member of the class Book
public:
void TotalPages(int NumPages) // member function definition
{
PageCount = NumPages;
}
void SetPage(int PageNumber) // member function definition
{
CurrentPage=PageNumber;
}
int GetCurrentPage() // member function definition
{
return CurrentPage;
}
}; // end of class definition
1 9
CLASSES AND OBJECTS
/* Main function */
void main()
{
Book MyBook;
MyBook.TotalPages(525);
MyBook.SetPage(152);
cout << Current Page << MyBook.GetCurrentPage() <<endl;
}
OUTPUT Current Page 152
In themain()an object variableMyBook of type Book is created. The total pages
of the book is set wi th the value 525 by call ing the member functi on
MyBook.TotalPages(). Then the method MyBook.SetPage() is called and the value
152 assigned to the object variable CurrentPage. Thencoutoutputs this value by calling
the MyBook.GetCurrentPage() method.
Program 3.8: A C++ program tosum the following series using object oriented programming
technique.
Sum = 1 + 2 + 3 + 4 + ........+n sum of natural numbers
Odd Sum = 1 + 3 + 5 + 7 + ........+n sum of odd numbes
Even Sum = 2 + 4 + 6 + 8 + ........+n sum of even numbers
#include <iostream.h>
class Series
{
private :
int m,sum,i;
public :
void SetData(int); // member function declaration
int Sum(); // member function declaration
int OddSum(); // member function declaration
int EvenSum(); // member function declaration
void DisplayInfo(); // member function declaration
}; // end of class definition
void Series::SetData(int n) // member function definition
{
m=n;
}
int Series::Sum() // member function definition
{
for(i=1,sum=0;i<=m;i++)
sum=sum+i;
return sum;
}
int Series::OddSum() // member function definition
{
for(i=1,sum=0;i<=m;i=i+2)
sum=sum+i;
return sum;
}
2 0 CLASSES AND OBJECTS
int Series::EvenSum() // member function definition
{
for(i=2,sum=0;i<=m;i=i+2)
sum=sum+i;
return sum;
}
void Series::DisplayInfo() // member function definition
{
cout << "Sum of natural numbers =" << Sum() << endl;
cout << "Sum of odd numbers =" << OddSum() << endl;
cout << "Sum of even numbers =" << EvenSum() << endl;
}
/* Main function */
void main()
{
int n;
Series S;
cout << "Input limit of the series :"; cin >> n;
S.SetData(n); // Assign values to data member of the class
S.DisplayInfo();
}
OUTPUT Input limit of the series : 10
Sum of natural numbers = 55
Sum of odd numbers = 25
Sum of even numbers = 30
3.7 ACCESSOR AND MUTATOR FUNCTIONS
Consider a class Series, discussed in the previous program. This class may
include certain member functions, the function SetData()sets the value of the member
variable m to the value specified i.e., n by the user. The member functions
Sum(),OddSum() and EvenSum() modify the data members (sum and i) of the class
Series. On the other hand certain function such as DisplayInfo() only access the
value of sum member variable. They do not modify the member variables. We can,
therefore, categorize the member functions of the class Series into two categories.
The member functions that modify the
member variables and member functions
that only access, and do not modify, the
member variables.
This is typically true for any class.
That is, every class has member functions
that only access and do not modify the
member variables they are called accessor
functions, and member functions that
modify the member variables are called
mutator functions.
3.8 ARRAY AS CLASS MEMBER DATA
Accessor function: A member function of
a class that only accesses i.e., does not
modify the values of the member variables.
Mutator function: A member function of a
class that modi fi es the values of the
member variables.
Definition
Array can be used as data member of classes. An array can be used as private
or public members of a class. This is illustrated in the following program.
2 1
CLASSES AND OBJECTS
Program 3.9: A C++ program to read and write N numbers into one dimensional array
using object oriented programming technique.
#include <iostream.h>
#include <iomanip.h>
class OneDimArray
{
private :
int a[100],m;
public :
void SetNoOfElements(int n) // member function definition
{
m=n;
}
void ReadArray(); // member function declaration
void DisplayArray(); // member function declaration
};
void OneDimArray::ReadArray() // member function definition
{
cout << "Enter " << m << " array elements" << endl;
for(int i=0;i<m;i++)
cin >> a[i];
}
void OneDimArray::DisplayArray() // member function definition
{
cout << "Array elements are :" << endl;
for(int i=0;i<m;i++)
cout << a[i] << setw(6);
}
/* Main function */
void main()
{
int n; // number of elements
OneDimArray A; // Create an object A of one dimension
cout << "Input number of elements :"; cin >> n;
A.SetNoOfElements(n); // set number of elements in the array
A.ReadArray();
A.DisplayArray();
}
OUTPUT Input number of elements : 6
Enter 6 array elements
5 6 7 8 92 32
Array elements are :
5 6 7 8 92 32
The array variable a[100] is a private member of the class OneDimArray. An
int variable m indicates number of elements in the array. This value is set by calling
the member function SetNoOfElements() from the main function. Array elements
can be entered only through the member function ReadArray() and elements can be
printed on the screen only through the member function DisplayArray()
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 <iostream.h>
#include <iomanip.h>
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 << "Enter " << m << " array elements" << endl;
for(int i=0;i<m;i++)
cin >> a[i];
}
void OneDimArray::DisplayInfo()
{
cout << "Array elements are :" << endl;
for(int i=0;i<m;i++)
cout << a[i] << setw(10);
cout << endl << "Maximum number =" << FindMax();
cout << endl << "Minimum number =" << FindMin();
cout << endl << "Average of " << m << " numbers =" << FindAverage();
}
int OneDimArray::FindMin()
{
int min = a[0];
for(int i=1;i<m;i++)
if( min > a[i]) min=a[i];
return min;
}
int OneDimArray::FindMax()
{
int max = a[0];
for(int i=1;i<m;i++)
if( max < a[i]) max=a[i];
return max;
}
float OneDimArray::FindAverage()
{
float sum = 0;
for(int i=0;i<m;i++)
sum = sum + a[i];
return sum / m;
}
int array a[] included as private
data member of the class.
2 3
CLASSES AND OBJECTS
/* Main function */
void main()
{
int n; // number of elements
OneDimArray A;
cout << "Input number of elements "; cin >> n;
A.SetDimension(n);
A.ReadArray();
A.DisplayInfo();
}
OUTPUT Input number of elements : 6
Enter 6 array elements
5 6 -7 8 -2 13
Array elements are :
5 6 -7 8 -2 13
Maximum number = 13
Minimum number = -7
Average of 6 numbers = 3.83333
The array variable a[] is a private member of the class OneDimArray. The
member function FindMin() returns the maximum of the array a[]. Similarly, the
member function FindMin() returns minimum of the array a[] and the member function
FindAverage()finds the average on N numbers. All these member functions are nested
in the DisplayInfo() member function of the class OneDimArray.
We can also include character array as a class member data. The following
program 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 following
information from the keyboard.
Register number
Name of the student
combination
Marks
Address
Display the result on the screen using a member function DisplayStdInfo().
#include <iostream.h>
class Student
{
private :
long RegNo;
char Name[20];
char Comb[6];
int Marks;
char Address[40];
public :
void ReadStdInfo() // member function definition
{
cout << "Enter register number :"; cin >> RegNo;
cout << "Enter the student name :"; cin >> Name;
cout << "Enter the combination :"; cin >> Comb;
cout << "Enter the marks :"; cin >> Marks;
cout << "Enter the Address :"; cin >> Address;
}
Decl ared three arrays of
character as data memebers of
a class
2 4 CLASSES AND OBJECTS
void DisplayStdInfo() // member function definition
{
cout << "Register number:" << RegNo << endl;
cout << "Name :" << Name << endl;
cout << "Combination :" << Comb << endl;;
cout << "Marks :" << Marks << endl;;
cout << "Address :" << Address << endl;;
}
}; // end of class definition
/* Main function */
void main()
{
Student S; // create a Student object
S.ReadStdInfo();
S.DisplayStdInfo();
}
OUTPUT Enter register number : 102013
Enter the student name : SUMUKHA
Enter the combination : PCMC
Enter the marks : 567
Enter the Address : Bangalore
Register number : 102013
Name : SUMUKHA
Combination : PCMC
Marks : 567
Address : Bangalore
In the above program, the student name is represented by an array of character
Name[20], the combination by Comb[6] and address of the student by an array of character
Address[40]. These arrays are used to represent data members of a class Student.
Program 3.11: Create a class called Matrix that contains two dimensional array and
order of the matrix. Use public functions called ReadMatrixOrder() to read order of the
matrix, MatrixRead() to read matrix elements and MatrixPrint() to print the matrix in the
matrix format.
#include <iostream.h>
#include <iomanip.h>
class Matrix
{
private :
int a[10][10]; // a is a two dimensional array
int R,C; // R is number of rows, C is number of columns
public :
void ReadMatrixOrder(); // member function declaration
void MatrixRead(); // member function declaration
void MatrixPrint(); // member function declaration
}; // end of class definition
void Matrix::ReadMatrixOrder() // member function definition
{
cout << Input number of Rows ; cin >> R;
cout << Input number of Columns ;cin >> C;
}
2 5
CLASSES AND OBJECTS
void Matrix::MatrixRead() // member function definition
{
cout << Input matrix elements << endl;
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
cin >> a[i][j];
}
void Matrix::MatrixPrint() // member function definition
{
cout << setw(20) << Matrix is << endl;
for(int i=0;i<R;i++)
{
for(int j=0;j<C;j++)
cout << setw(8) << a[i][j];
cout << endl;
}
}
/* Main function */
void main()
{
Matrix X; // create an object of type matrix
X.ReadMatrixOrder();
X.MatrixRead();
X.MatrixPrint();
}
OUTPUT Input number of Rows 3
Input number of Columns 3
Input matrix elements
1 2 3 4 5 6 7 8 9
Matrix is
1 2 3
4 5 6
7 8 9
Program 3.12: Create a class called CricketData that contains the data of a player.
Input data for a player. Use a menu driven program to display either the entire data or
just the name or the total runs scored in the last three matches. Repeat the process
for more players.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class CricketData
{
private:
char Name[30];
int MatchRuns[4];
int TRuns;
Decl ared charact er array as
data member of a class
Declared integer array as data
member of a class
2 6 CLASSES AND OBJECTS
public:
void ReadData();
int TotalRuns();
void ShowData();
void ShowName();
}; // end of class definition
void CricketData::ReadData()
{
cout<<"Enter player name : ";
cin >> Name;
cout<<"Input four matches runs : "<<endl;
for(int i=0; i<4;i++)
{
cout << "Input match " << i+1 << " Run(s)=";
cin >> MatchRuns[i];
}
TotalRuns();
}
int CricketData::TotalRuns()
{
TRuns =0;
for(int i=0;i<4;i++)
TRuns = TRuns + MatchRuns[i];
return TRuns;
}
void CricketData::ShowData()
{
cout<<"Player name : "<<Name<<endl;
for(int i=0; i<4;i++)
cout << "Match " << i+1 << " Run(s)=" << MatchRuns[i] << endl;
cout<<"Total run(s) : "<< TotalRuns()<<endl;
}
void CricketData::ShowName()
{
cout << endl << "Name of the player = " << Name;
cout << endl;
}
/* Main function */
void main()
{
clrscr();
int choice;
char ans='n';
CricketData Player;
Player.ReadData();
do
{
cout<<" 1. Show Data"<<endl;
cout<<" 2. Show Player Name"<<endl;
cout<<" 3. Show Total runs scored"<<endl;
cout<<" 4. Exit"<<endl;
cout<<"\n Enter any one of the options : ";
cin>>choice;
2 7
CLASSES AND OBJECTS
switch(choice)
{
case 1: Player.ShowData();
break;
case 2: Player.ShowName();
break;
case 3: cout<<"Total runs in 4 mathces"<< Player.TotalRuns();
break;
case 4: exit(0);
break;
default: cout<<"\n Enter choice (1 to 4)";
}
cout<<endl<<"Do you want to choose any other option?(y/n)"<<endl;
cin>>ans;
clrscr();
}while(ans=='y'||ans=='Y');
getch();
}
OUTPUT Enter player name : TANDULKAR
Input four matches runs :
Input match 1 Run(s)= 104
Input match 2 Run(s)= 0
Input match 3 Run(s)= 89
Input match 4 Run(s)= 123
1. Show Data
2. Show Player Name
3. Show Total runs scored
4. Exit
Enter any one of the options :1
Player name : TANDULKAR
Match 1 Run(s)= 104
Match 2 Run(s)= 0
Match 3 Run(s)= 89
Match 4 Run(s)= 123
Total run(s) : 316
Do you want to choose any other option?(y/n) Y
1. Show Data
2. Show Player Name
3. Show Total runs scored
4. Exit
Enter any one of the options :2
Name of the player = TANDULKAR
Do you want to choose any other option?(y/n) Y
1. Show Data
2. Show Player Name
3. Show Total runs scored
4. Exit
Enter any one of the options :4
2 8 CLASSES AND OBJECTS
3.9 CLASSES, OBJECTS AND MEMORY
Objects are the identifiers declared for class elements. Object is a composition
of one more variable declared in the class. Each object has its own copy of public and
private data members. An object can access to its own copy of data members and
have no access to data members of other objects.
We have stated that the class declaration does not allocate memory to the class
data member. When an object is declared, memory is reserved for only data members
and 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 <iostream.h>
class Student
{
private :
long RegNo; // 4 bytes of memory
char Name[20]; // 20 bytes of memory
char Comb[6]; // 6 bytes of memory
int Marks; // 2 bytes of memory
char Address[40]; // 40 bytes of memory
public :
void ReadStdInfo();
void DisplayStdInfo();
}; // end of class definition
void main()
{
Student S1,S2; // Total 72 bytes for S1 and 72 bytes for S2
cout << "Size of the object S1 is =" << sizeof(S1)<< endl;
cout << "Size of the object S2 is =" << sizeof(S2)<< endl;
cout << "Size of the class is =" << sizeof(Student);
}
OUTPUT Size of the object S1 is = 72
Size of the object S2 is = 72
Size of the class is = 72
In the above program, the class Student has five data members of long RegNo
(4 bytes), character array Name[20] (20 bytes), character array Comb[6] (6 bytes),
int Marks(2 bytes) and character array Address[40] (40 bytes). The S1 and S2 are two
objects of the class Student. The sizeof operator returns the size of the objects as
well as size of the class. The size of the any object is equal to the sum of sizes of all the
data members of the class. Here, the function sizeof operator returns 72, which is
the size of an individual object.
The member functions are not considered in the size of the object. All the objects
of a class use the same member functions. The member functions are created and
placed in the meory space only once when they are defined as a part of a class
specifications. Since all the objects belongs to that class use the same member functions,
no separate space is created for member functions when the objects are created. The
Figure 3.8 illustrate the concept of data members and member functions in memory.
2 9
CLASSES 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, class
and typedef. We can also create an array of objects. The declaration of an array of
class 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 of
objects 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 array
PUC[5] contains IdNo, Name and Marks information for five objects. Similarly, the
DEGREE 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, Name
and Marks.
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
class Student
{
private :
int IdNo;
char Name[20];
int Marks;
public :
void ReadData( )
{
cout << "Enter the following information" << endl;
cout << "IdNo :"; cin >> IdNo;
cout << "Name :"; cin >> Name;
cout << "Marks :"; cin >> Marks;
}
void DisplayData( )
{
cout << setw(5) << IdNo << setw(15) <<Name;
cout << setw(7) << Marks << endl;
}
}; // end of class definition
/* Main function */
void main( )
{
Student COLLEGE[100];
int N,i;
clrscr();
cout << "Input number of students :";
cin >> N; // N is number of students in a college
3 1
CLASSES AND OBJECTS
for(i=0;i <N;i++)
COLLEGE[i].ReadData();
cout << "-------------------------------"<<endl;
cout << "LIST OF STUDENTS IN ABC COLLEGE"<<endl;
cout << "-------------------------------"<<endl;
cout <<"IdNo"<< setw(15) << "Name" << setw(9) << "Marks" << endl;
for(i=0;i < N ;i++)
COLLEGE[i].DisplayData( );
cout << "-------------------------------"<<endl;
getch();
}
OUTPUT Input number of students : 3
Enter the following information
IdNo :101
Name :SHEKAR
Marks :430
Enter the following information
IdNo :102
Name :UDAY KUMAR SOORI
Marks :550
Enter the following information
IdNo :103
Name :ARJUN
Marks :230
-------------------------------
LIST OF STUDENTS IN ABC COLLEGE
-------------------------------
IdNo Name Marks
101 SHEKAR 430
102 UDAY KUMAR SOORI 550
103 ARJUN 230
-------------------------------
Program 3.15: Program to create a class Employee to hold the data of an employee
such as EmployeeCode, Name, Designation, BasicSalary, HRA and DA. Use a function to
calculate the total salary. Input data for N employees and output the data of all the
employees with proper headings.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class Employee // Class definition
{
private:
int EmpCode;
char EmpName[20];
char Design[20];
float BasicSalary,HRA,DA,NetSalary;
float ComputeNetSalary(); // private member function
public:
void ReadEmpInfo();
void DisplayInfo();
}; // end of class definition
3 2 CLASSES AND OBJECTS
float Employee::ComputeNetSalary()
{
return (BasicSalary+HRA+DA);
}
void Employee::ReadEmpInfo()
{
cout <<"Enter the employee code:"; cin >> EmpCode;
cout <<"Enter the employee name:"; cin >> EmpName;
cout <<"Enter designation:"; cin >> Design;
cout <<"Enter the basic salary:"; cin >> BasicSalary;
cout <<"Enter HRA:"; cin>>HRA;
cout <<"Enter DA:"; cin>>DA;
}
void Employee::DisplayInfo()
{
cout<<setw(6) << EmpCode << setw(15) << EmpName;
cout<<setw(10) << Design << setw(10) << ComputeNetSalary();
}
/* Main function */
void main()
{
Employee E[10];
int i,n;
clrscr();
cout<<endl<<"Enter the number of employees :";
cin>>n;
cout << "Input Employee information " << endl;
for(i=0;i<n;i++)
E[i].ReadEmpInfo();
cout<<"------------------------------------------------"<<endl;
cout<< setw(6) << "Code" << setw(12) << "Name";
cout<< setw(16) << "Designation" << setw(12) << "Net Salary" <<endl;
cout<<"------------------------------------------------"<<endl;
for(i=0;i<n;i++)
{
E[i].DisplayInfo();
cout<<endl;
}
cout<<"------------------------------------------------"<<endl;
getch();
}
OUTPUT Enter the number of employees:3
Input Employee information
Enter the employee code:100
Enter the employee name:Varun
Enter designation:CEO
Enter the basic salary:250000
Enter HRA:15000
Enter DA:12000
ComputeNetSal ary i s a
private member function of
the class and we can access
from the publ i c member
functions of the class.
ComputeNetSal ary has no
access to main function
3 3
CLASSES AND OBJECTS
Enter the employee code:101
Enter the employee name:Vinay
Enter designation:Manager
Enter the basic salary:15000
Enter HRA:1600
Enter DA:1000
Enter the employee code:102
Enter the employee name:Madhu
Enter designation:Attender
Enter the basic salary:5000
Enter HRA:1000
Enter DA:500
------------------------------------------------
Code Name Desig Salary
------------------------------------------------
100 Varun CEO 277000
101 Vinay Manager 17600
102 Madhu Attender 6500
------------------------------------------------
In the above program the member function ComputeNetSalary() is defined under
private section of the class Employee. This private member function has the strict
access control. Only the member functions of the same class can access this member
function. The private members of the class are inaccessible outside the class (in the
main() 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 any
other type of data is passed. Simply declare the functions parameter as a class type
and use an object of that class as an argument when calling the function. As with other
types of data, by default all objects are passed by value to a function. The Program 3.16
demonstrates 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 and
Maths marks
Public Member functions:
i. Function ReadMarks() to read an object Exam which contains marks of
Physics, 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 <iostream.h>
#include <conio.h>
3 4 CLASSES AND OBJECTS
class Exam // class definition
{
private :
float Physics,Chemistry,Maths;
public :
void ReadMarks()
{
cout <<"Input Physics marks :"; cin >> Physics;
cout <<"Input Chemistry marks:"; cin >> Chemistry;
cout <<"Input Maths marks :"; cin >> Maths;
}
void DisplayInfo()
{
cout << "Physics :" << Physics << endl;
cout << "Chemistry :" << Chemistry << endl;
cout << "Maths :" << Maths << endl;
}
void Total(Exam PU ,Exam CT )
{
Physics = PU.Physics + CT.Physics;
Chemistry = PU.Chemistry + CT.Chemistry;
Maths = PU.Maths + CT.Maths;
}
}; // end of class definition
/* Main function */
void main()
{
Exam PUC,CET,PUCplusCET;
clrscr();
cout << "Enter PUC marks" << endl << endl;
PUC.ReadMarks(); // Read PUC marks
cout <<endl<<"Enter Common Entrance Test marks"<<endl;
CET.ReadMarks(); // Read CET marks
PUCplusCET.Total(PUC , CET ); //Calling function with two object arguments
cout << endl << "Total marks of PUC and CET is:" << endl<<endl;
PUCplusCET.DisplayInfo();
}
OUTPUT Enter PUC marks
Input Physics marks : 67
Input Chemistry marks: 89
Input Maths marks : 80
Enter Common Entrance Test marks
Input Physics marks : 60
Input Chemistry marks: 76
Input Maths marks : 91
Total marks of PUC and CET is:
Physics : 127
Chemistry : 165
Maths : 171

P
U
C

M
a
r
k
s
C
E
T

M
a
r
k
s
3 5
CLASSES 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 CET
objects 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 the
object PUC and CET as arguments. This function directly access the Physics, Chemistry
and Maths variables of PUCplusCET. The member of PUC and CET can be accessed only by
using 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 and
DisplayTime() to display time.
#include <iostream.h>
#include <conio.h>
class Time
{
private :
int ss,mm,hh;
public :
void ReadTime()
{
cout << " time (hh:mm:ss) ";
cin >> hh >> mm >> ss;
}
3 6 CLASSES AND OBJECTS
void DisplayTime()
{
cout << endl <<"Time is =" << hh << ":" << mm << ":" << ss;
}
void AddTime( Time T1, Time T2)
{
mm=hh=0;
ss = T1.ss + T2.ss;
if( ss >= 60) // if total exceeds 60
{ // then add minute
mm++; // by 1 and
ss=ss-60; // decrease seconds by 60
}
mm += T1.mm + T2.mm;
if( mm >= 60) // if total exceeds 60
{ // then add hours by
hh++; // by 1 and
mm=mm-60; // decrease minutes by 60
}
hh += T1.hh + T2.hh;
}
}; // end of class definition
/* Main program */
void main()
{
Time TIME1, TIME2,TIME3; // Define three time objects
cout << endl<<"Input First Time ";
TIME1.ReadTime(); // Get first time from user
cout <<endl<< "Input Second Time";
TIME2.ReadTime(); // Get second time from user
TIME3.AddTime(TIME1,TIME2); // Add two times
TIME1.DisplayTime();
TIME2.DisplayTime();
TIME3.DisplayTime(); // Display sum of two times
}
OUTPUT Input First time (hh:mm:ss) 12 35 38
Input Second time (hh:mm:ss) 12 35 32
Time is = 12:35:38
Time is = 12:35:32
Time is = 25:11:10
3.12 RETURNING OBJECTS FROM FUNCTIONS
In the program 3.16 and program 3.17 we saw objects being passed as arguments
to functions. The functions can also return objects. To do so, first declare the function
as returning a class type. Second, return an object of that type using the normal return
statement. We will modify the program 3.16 to return object from the member function.
3 7
CLASSES AND OBJECTS
Program 3.18: Define a class called Exam which has the following members:
Private Data members:
Physics marks,
Chemistry marks and
Maths marks
Public Member functions:
i. Function ReadMarks() to read an object Exam which contains marks of
Physics, 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 <iostream.h>
#include <conio.h>
class Exam // class definition
{
private :
float Physics,Chemistry,Maths;
public :
void ReadMarks()
{
cout <<"Input Physics marks :"; cin >> Physics;
cout <<"Input Chemistry marks:"; cin >> Chemistry;
cout <<"Input Maths marks :"; cin >> Maths;
}
void DisplayInfo()
{
cout << "Physics :" << Physics << endl;
cout << "Chemistry :" << Chemistry << endl;
cout << "Maths :" << Maths << endl;
}
Exam Total(Exam CT )
{
Exam Temp; // Temporary object which holds the sum
Temp.Physics = Physics + CT.Physics;
Temp.Chemistry = Chemistry + CT.Chemistry;
Temp.Maths = Maths + CT.Maths;
return Temp;
}
}; // end of class definition
/* Main function */
void main()
{
Exam PUC,CET,PUCplusCET;
clrscr();
cout << "Enter PUC marks" << endl << endl;
Function receives one object
Return
value
of the
Function
is an object
PUCplusCET = PUC . Total( CET )
3 8 CLASSES AND OBJECTS
PUC.ReadMarks(); // Read PUC marks
cout <<endl<<"Enter Common Entrance Test marks"<<endl;
CET.ReadMarks(); // Read CET marks
PUCplusCET=PUC.Total( CET ); // Calling function with one object
cout << endl << "Total marks of PUC and CET is:" << endl<<endl;
PUCplusCET.DisplayInfo();
}
OUTPUT Enter PUC marks
Input Physics marks : 88
Input Chemistry marks: 96
Input Maths marks : 100
Enter Common Entrance Test marks
Input Physics marks : 99
Input Chemistry marks: 100
Input Maths marks : 100
Total marks of PUC and CET is:
Physics : 187
Chemistry : 196
Maths : 200
The above program operates just the same as the program 3.15. In this program
Exam, CET is passed to Total() as an argument. It is added to the object, PUC, of which
Total()is a member, and the result is returned from the function. In main() the
result is assigned to PUCplusCET, in the statement
PUCplusCET=PUC.Total(CET);
There is one important point to understand about returning objects from
functions, however: When an object is returned by a function, a temporary object is
automatically created which holds the return value. It is this object that is actually
returned by the function. After the value has been returned, this object is destroyed.
The destruction of this temporary object might cause unexpected side effects in some
situations.
What is the purpose of a class definition?
A class definition describes how objects of a class will look when they are created.

You might also like