You are on page 1of 11

March 2, 2016 Lab - 04

Student Name: __________________________Roll No: ______________ Section: ______________

LAB - 04
Functions, and
Introduction to Classes and Objects
To explore and understand the use, need and implementation of C++ functions
and classes.

1. Functions
A function groups a number of program statements into a unit and gives it a name. This unit can then be
invoked from other parts of the program. One of the reasons to use functions (and the reason they were
invented, long ago) is to reduce program size. Any sequence of instructions that appears in a program more
than once is a candidate for being made into a function. The function’s code is stored in only one place in
memory, even though the function is executed many times in the course of the program. The figure below
shows how a function is invoked from different sections of a program.

Functions can either be library defined or user defined. Library functions are built in functions which are
defined by C++ library, for example exit(), sqrt(), strcmp() etc. The components that are necessary to add a
function to the program are three: the function declaration, the calls to the function, and the function
definition.
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

Component Purpose Example


Declaration Specifies function name, argument types, and return value. void func1();
(prototype) Alerts compiler (and programmer) that function is coming up
Function later. the function to be executed.
Causes func1();
Call
Definition The function itself. void func1()
function. Contains the lines of code that constitute the function. {
// lines of code
}

The figure shows the syntax of the function declaration, function call, and function definition.
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

Example Program – 1
#include <iostream>

using namespace std;

void starline(); //function declaration // (prototype)

int main()
{
starline(); //call to function

cout << “Data type Range” << endl;

starline(); //call to function

cout << “char -128 to 127” << endl

<< “short -32,768 to 32,767” << endl

<< “int System dependent” << endl

<< “long -2,147,483,648 to 2,147,483,647” << endl;

starline(); //call to function

return 0;
}
//--------------------------------------------------------------
// starline() // function definition

void starline() //function declarator


{
for(int j=0; j<45; j++) //function body

cout << ‘*’;

cout << endl;

The output from the program looks like this:


*********************************************
Data type Range
*********************************************
char -128 to 127
short -32,768 to 32,767
int System dependent
long -2,147,483,648 to 2,147,483,647
*********************************************
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

2. Classes and Objects


Object:
In OOP an object is a very much like a real world object. An object can be defined as a collection of state
and behavior. For example, consider the example of a cat. A cat is has both a state and behavior. The state of
a cat is its attributes namely color, breed, gender, age, weight, height, etc. Whereas the behavior of a cat is its
sound, eating, sleeping, yawning, walk, etc. Hence a cat can be completely identified by its unique
characteristics and behaviors.

In programming an object is a collection of variables and functions that together have a unique purpose of
identifying a distinctive entity.

Data Members:
Again referring to the concept of an object and the example of a cat. The cat had a number of characteristics
or attributes that can be used to identify a cat. In programming these attributes can be programmed by using
regular variables that are called data members. A class can be composed of a number of data members of
various types. The data members of a class are private by default i.e. they are not directly accessible outside
the class.

Here it is important to point out that often people casually refer to these as variables, which is a wrong
terminology. These should only be called data members or class variables.

Member Functions:
Again referring to the concept of an object and the example of a cat. The cat had a number of behaviors or
things that a cat does. In programming these behaviors can be programmed by using functions that are called
member functions. A class can be composed of a number of member functions of various types.
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

Data Reusability:
This term refers to the ability for multiple programmers to (or multiple time) use the same written and
debugged existing class of data. This is a time saving device and adds code efficiency to the language.
Additionally, the programmer can incorporate new features to the existing class, further developing the
application and allowing users to achieve increased performance. This time saving feature optimizes code,
helps in gaining secured applications and facilitates easier maintenance on the application.

Data Encapsulation:
Data Encapsulation combines data and functions into a single unit called Class. When using Data
Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the
class. Data Encapsulation enables the important concept of data hiding possible.

Class:
A class is a collection of data members and member functions. A class is used to define an abstract data type.
This abstract data type is used in the construction of an object which is used to access all the data members
and member functions. A class has to be created before it can be used.

Relationship between object and class:


An object has the same relationship to a class that a variable has to a data type. An object is said to be an
instance of a class, in the same way an apple is an instance of a fruit. The difference between classes and
implicit data types is that objects are reference types (passed by reference) while implicit data types are
value type (passed by making a copy).

When you define a class, you declare the data that it contains and the code that operates on it. While very
simple classes might contain only code or only data, most real-world classes contain both.

Example Program – 2
The class small obj defined in this program contains one data item and two member functions. The two
member functions provide the only access to the data item from outside the class. The first member function
sets the data item to a value, and the second displays the value.

Placing data and functions together into a single entity is a central idea in object-oriented programming.
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

3. A Simple Class through Example Program – 3

DEFINE A CLASS
To illustrate classes, we will be evolving a class that encapsulates information about buildings, such as
houses, stores, offices, and so on. This class is called Building, and it will store three items of information
about a building: the number of floors, the total area, and the number of occupants.

The first version of Building is shown here. It defines three variables: Floors, Area, and Occupants. Notice
that Building does not contain any methods. Thus, it is currently a data-only class.

Consider Example below


March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

The declaration starts with the keyword class, followed by the class name—Building. Like a structure,
the body of the class is delimited by braces and terminated by a semicolon
PRIVATE AND PUBLIC:
A key feature of object–oriented programming is data hiding. The term private means that data is
concealed within a class, so that it cannot be accessed mistakenly by functions outside the class. The
primary mechanism for hiding data is to put it in a class and make it private. Private data or functions can
only be accessed from within the class. Public data or functions, on the other hand, are accessible from
outside the class. If an access type is not mentioned, by default the members are considered private.

USE A CLASS
Now that the class is declared, let’s see how main() makes use of it. We’ll see how objects are defined.

DEFINING OBJECTS:
Object of the class Building can be defined as,

Building house;
After this statement executes, house will be an instance of Building. Remember that the declaration for
the class Building does not create any objects. It only describes how they will look when they are created.
It is the definition that actually creates objects that can be used by the program.
Defining an object is similar to defining a variable of any data type: 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.
Each time you create an instance of a class, you are creating an object that contains its own copy of each
instance variable defined by the class. Thus, every Building object will contain its own copies of the
instance variables Floors, Area, and Occupants. To access these variables, you will use the member
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

access operator, which is a period. It is commonly referred to as the dot operator. The dot operator links the name of
an object with the name of a member. The general form of the dot operator is shown here:

object.member
Thus, the object is specified on the left, and the member is put on the right. For example, to assign the
Floors variable of house the value 2, use the following statement:

house.Floors = 2;
In general, you can use the dot operator to access both instance variables and Functions.

Here is a complete program that uses the Building class:

Example Program – 3
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

MEMBER FUNCTIONS
Member functions are functions that are included within a class. (In some object–oriented languages member functions
are called methods; some writers use this term in C++ as well.) In example 01-b the Area per person can be calculated
using the below function:

public:

void AreaPerPerson()

{ cout<<" " << area / occupants << " area per person";

In order to use a function, you simply call the function along with the dot operator for each object. Like this:

house.AreaPerPerson();
This statement invokes the AreaPerPerson( ) method on house. That is, it calls AreaPerPerson( ) relative to the object
referred to by house, by use of the dot operator. In this case, the call to house.AreaPerPerson( ) displays the area-per-
person of the building defined by house.
In similar fashion, the call to office.AreaPerPerson( ) displays the area-per-person of the building defined by office.
Each time AreaPerPerson( ) is invoked, it displays the area-per-person for the specified object. There is something very
important to notice inside the AreaPerPerson( ) Function: The instance variables area and occupants are referred to
directly, without use of the dot operator. When a function uses a variable that is defined by its class, it does so
directly, without explicit reference to an object and without use of the dot operator. This is easy to understand if you
think about it. A function is always invoked relative to some object of its class. Once this invocation has occurred, the
object is known.

TIP: Usually the data within a class is private and the functions are public. This is a result of how classes are used. The
data is hidden so it will be safe from accidental manipulation, while the functions that operate on the data are public so
they can be accessed from outside the class. However, there is no rule that data must be private and functions public; in
some circumstances you may find you’ll need to use private functions and public data.
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

4. Setting Values via Member Functions


The value of an object of a class can be set using member functions. Consider Example 04

Example Program – 4
March 2, 2016 Lab - 04
Student Name: __________________________Roll No: ______________ Section: ______________

Student Tasks:
1. Attempt the example on page 163 of text book.

2. Write a function that finds the area of a circle. It should take an argument of type float and return an argument
of the same type. Write a main function that gets a radius value from user, call the function and display result.
Area = PI * radius * radius
PI= 3.14159F

3. Write a function called time_to_secs() that takes three int values for hour, minutes, and seconds as arguments,
and returns the equivalent time in seconds (type long). Create a program that exercises this function by
repeatedly obtaining a time value in hours, minutes, and seconds from user (format 12:59:59), calling the
function, and displaying the value of seconds in returns.

4. Write two functions namely add ( ) with different arguments passed in each function (add two double
variables, and add two integer variables in each function). Calling these functions in main () program and
displaying the result of each function separately.

5. Is it possible to exempt the function prototype? Re-attempt the example 1 without prototype in the beginning.

6. Reform example 1 such that the character to be printed and the number of times you want it to be printed is
given as input from the user.

7. Attempt the example on page 216 of text book.

8. Create a class called Fruit. Instantiate this class in main (create objects, 2), assign values against each
variable and print the values.

9. Attempt the example on page 226 of text book.

10. Create an employee class. The member data should comprise an int for storing the employee number and a
float for storing the employee’s compensation. Member function should allow the user to enter this data and
display it. Write a main () that allow the user to enter data for three employees. And display it.

You might also like