You are on page 1of 20

Lab 04

Fundamentals of Object-Oriented
Programming
Objective:
 Understand the object oriented programming paradigm.
 Understand the declaration of classes.
 Understand the data members, member functions and access specifiers.
 Understand the use of constructor and destructor functions.
 Understand the concept of encapsulation.
 Understand the use of passing objects as function arguments.

Introduction to Object Oriented Programming


We humans are very good recognizing and working with objects, such as a pen, a dog, or a human
being. We learned to categorize them in such a way that makes sense to us. We may categorize
them as animate object, inanimate objects, pets, friends, etc. We sometimes classify objects based
on their attributes, for example, green apples or red apples, fat or slim people, etc. If you think
about it each object has many attributes. If I ask you list the attributes of an orange, you probably
could list many things such as color, shape, weight, smell, etc.

In addition to attributes, all objects exhibit behaviors. A dog eats, barks, wags its tail, plays, and
begs. A dog exhibits many more other behaviors than this short list. It is a good idea to practice
listing attributes and behaviors of many of the objects you come across each day. Another thing
we need to remember about objects is that objects interact between each other.
Programmers, for over thirty years programmed using functions and procedures. Each function
and procedure was called to carry out certain tasks on the data that were given to it and to return
(or not return) certain results back. With this type of procedure oriented programming, we had to
adapt our thinking procedurally. Working with objects is a more normal and suitable approach for
human beings. Such programming approach is called Object Oriented Programming (OOP).

In Object Oriented Programming, objects are packages that contain data and functions (methods)
that can be performed on the data. Data could be considered to be attributes and functions are

Department of Electrical Engineering 40


considered to be behaviors of the object. We can say that the attributes and behaviors are
encapsulated into an object. The objects interact between each other through their interfaces. As
an example a date object may have a set of data consisting of month, day and year, and methods
consisting of assign date, display date, yesterday and tomorrow.

Data abstraction is another important feature of Object oriented programming. OOP hides the
details of data structures from the users. For example, to set a date in the aforementioned example,
values of month, day and year are passed to the assign-date method. The actual representation of
the date is hidden from the user.

There can be various objects made of a particular class (recall that many variables can be made
from type). In OOP the general type with which objects can be made is called a class. An object is
an instance of a class. Each class contains data (data members) as well as set of functions (member
functions) that manipulate the data.

Defining Classes:
A class is defined in a similar way as a structure is defined. The keyword “class” is used to
define the class. The general syntax to define a class is:

class Class_name
{
Body of class
};

1. Components of a Class:

A class consists of four different components that are

 Data members
 Member functions
 Access modifiers
 Constructors
 Destructor

1.1. Data members

Variable that we define inside a class are called data members of class.
Department of Electrical Engineering 41
1.2. Member Functions

The functions of a class that are defined to work on its data


members are called member functions of the class. The member
functions may be defined within the class or outside it. A class is
defined in the given example (Figure 6.1) which has three data
members and two member functions.

1.3. Access modifiers

The keyword that determine whether a member of a class can be


accessed from outside the class or not are called member access
specifies. There are three types of access specifiers. These are
private, public and protected. We will study protected specifiers
in next lab.

1.3.1 Private Specifiers

The members of a class that we don’t want to access from outside of the class are declared under
the private scope. We use private: keyword to specify the private scope. See (Figure 6.1).

All class members that come after the access specifier private: and up to the next access specifiers
are declared as private and are accessible only from inside the class. The default access mode is
private.
Note: if no access modifier is given, the data member is treated as private.
Restricting data members to be accessed from within the class is called “data hiding”, i.e. the data
members declared as private is hidden from outside the class. Data hiding is also known as
“encapsulation”.

1.3.2 Public Specifiers

Public members of a class can be accessed both from inside and from outside the class. We use
public: keyword to specify the public scope. See (Figure 6.1). Normally, member functions are
declared as public.

Department of Electrical Engineering 42


1.4. Constructors

We use constructors to initialize the data members of the class. Constructor has no return type and
it is defined with the name of class in public scope as shown in (Figure 6.3).
There are two types of constructors
 Default constructor
 Parameterized constructor

1.4.1. Default constructors

Constructor which has not argument is called default constructor. We defined the default
constructor to initialize the data members of class with default values. See (Figure 6.3)

Department of Electrical Engineering 43


1.4.2. Parameterized constructors

Constructor having one or more parameters is called parameterized constructor. See (Figure 6.3)

Department of Electrical Engineering 44


1.4.3. All-purpose constructor:
You can define a constructor in such a way that can behave like a parameterized constructor as
well as default constructor.

For example:
You can define all-purpose constructor for program (Figure 6.4) by this way

(Figure 6.4)

The above constructor will behave as default and parameterized both. You don’t need to define
constructor with no parameters.

If you have defined a parameterized constructor by this way and you never supply values to it then
the compiler will create a default constructor for you and initialized the data members with those
values which are assigned in parameters.

If you supply one value then it will assign the supplied value to first parameter and then set default
values to other parameters.

1.5. Destructor

When an object is destroyed, a special


member function of the class is executed
automatically. This member function is called
destructor. The destructor function has the
same name as the name of class but a tilde
sign (~) is written before its name. It is
executed automatically when an object comes
to the end of its life. Like constructors,
destructors do not have any return type. They
also don’t take any argument. The destructor
function is commonly used to free the
memory that was allocated for objects. See
(Figure 6.4).

Department of Electrical Engineering 45


When you run the following program, it declares an object of type Person in main function and
call default constructor with the object. When the main program end, compiler automatically calls
destructor of the class because, life of object becomes end.

Setters and Getters


Setters and getters are the functions that are used to set and get the values of data member from
outside the class. See (Figure 6.1). In the given example, setter and getter are defined in public
scope for data member number.

Setter has normally void data type and one parameter with same data type for which it is declared.
Normally setters and getters are declared with the name of data member including “set or get” as
prefix, to increase the readability and understanding.

Objects of Class
Object is a variable of type class. We declare objects
with the name class because class is a data type. Object
is also known as instance of class. Each object consists
of both data members and the member functions of the
class. Combining the both data member and functions
into one unit is called data encapsulation. See (Figure
6.2).

Default Copy Constructor

The copy constructor is a constructor which creates


an object by initializing it with an object of the same
class, which has been created previously. The copy
constructor is used to:

 Initialize one object from another of the same type.


 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.

Department of Electrical Engineering 46


If a copy constructor is not defined in a class, the compiler itself defines an copy constructor which
is called copy constructor.

Example:
#include<iostream>
using namespace std;
class Truck
{
private:
int number;
int model;
public:
// parameterized constructor
Truck(int _number=0, int _model=0)
{
number = _number;
model = _model;
}
//setters and getters
void setNumber(int _number)
{
number = _number;
}
int getNumber()
{
return number;
}
void setModel(int _model)
{
model = _model;
}
int getModel()
{
return model;
}
};

void main()
{
Truck truck1 (102 , 2014 , 30000); //supplied values to parameterized constructor

Truck truck2 =truck1; //This will call copy constructor

cout << truck2.getModel () << endl;


cout << truck2.getNumber () << endl;
cout << truck2.getPrice () << endl;
}

Department of Electrical Engineering 47


If you look in the main function, I have declared an object “truck1” of class Truck and called a
parameterized constructor. Then I declared another object “truck2” of the same class and assigned
truck1 to truck2. On the execution of this line, compiler defines a constructor at run time to copy
the contents of truck1 object into truck2 object.
Output of the above program is:

Department of Electrical Engineering 48


Activity 01: (30 minutes)
Demonstration of class, its data members, member functions with access modifiers.
The following program has a class Student with data members name, address and
cgpa in private scope. It has one default and one overloaded constructor in public scope.
It also has setters and getters for data members. In main functions, we have defined an
object s1 with data type Student. Overloaded constructor is also called while declaring
the object. When this program executes, it first declares s1 and then pass the values to
overload constructor. After passing the values, it displays the information by using
getters of data members.
#include<iostream>
using namespace std;
class Student
{
private:
char *name;
char *address;
float cgpa;

public:
Student()//default constructor
{
cgpa = 0;
}
// overloaded constructor
Student(char *_name, char *_address, float _cgpa)
{
name = _name;
address = _address;
cgpa = _cgpa;
}
//setters and getters
void setName(char *_name)
{
name = _name;
}
char* getName()
{
return name;
}
void setCgpa(float _cgpa)
{
cgpa = _cgpa;
}
float getCgpa()
{
return cgpa;
}
};

Department of Electrical Engineering 49


int main()
{
Student s1 ( "Ali" , "Islamabad" , 3.6 );
cout << s1.getName() << endl; //getting name
cout << s1.getCgpa() << endl; //getting cgpa
return 0;
}
Activity 1.1:
Copy and paste the program in your compiler and define setter and getter for data
member address. Then display all information on console using the getter of data
member.

Activity 1.2:

Declare destructor for Student class and print “Object destroyed” using cout statement.
Run the program and see the output.

Activity 1.3:
Define all-purpose constructor for all data members of Student.

Then test the program in following ways:

 Call parameterized constructor with empty arguments and display all data
members on console.
 Call parameterized constructor with one argument and display all data members
on console.
 Call parameterized constructor by passing all arguments and display all data
members on condole.
Activity 1.4:
Declare another object “s2” of the same class and assign s1 to s2, then display all
information.

Department of Electrical Engineering 50


Activity 02: (45 minutes)
Activity 2.1:
Create a class called Time that has three data members int for hours, minutes, and
seconds. One constructor with zero arguments that initialize data members with to 0,
and another constructor with parameters that initialize data members to fixed values.
Write a member function that should display time in 11:59:59 format. In the main menu
declare two object t1 and t2 of type Time in main, t1 with default constructor and t2
another with parameterized constructor (you should pass time in parameters of
constructor). Set time on t1 by using the setters and getters of data members.

Activity 2.2:
Define a public member function calculateDuration in Time class that receive object
of type time and calculate the time difference to find out the duration and display on
screen.
Define following menu in main and get choice.

 Press 1 to set start time


 Press 2 to set end time
 Press 3 to display start time
 Press 4 to display end time
 Press 5 to calculate duration

Program should perform this task repeatedly.

Department of Electrical Engineering 51


Activity 2.3:
Define a function isEqual in Time class that compare two objects. If the objects are
equal then it return true and if the object are not equal then it return false.
Define case 6 to check the equality of t1 and t2 objects.

Practice Questions:
Question 1:
Create an Employee class with data members name, address, contactNo and designation in private
scope.

Define all-purpose parameterized constructor and two member function with name input and
display. Input function should get the input from user and should display all data members.
Define setters and getters of each data member.
Define main function. Declare 10 size array of type Employee
Ask the user to select choice from the following menu
Press 1 to add employee
Press 2 to display all employees
Press 3 to search employee
Press 4 to exit
Program should exit only when user select option 4.

Question 2:

Develop a banking system which provides facility to create accounts, display accounts
information, deposit amount, withdraw amount, and check balance.

To do this, you have to create a class which should have some data members and functions to
perform the given operations.

Your system also has a business rule that, to open a new account, each user has to deposit 500
hundred rupees.

Department of Electrical Engineering 52


Question 3:

Step 1:
Define a class Accounts with data members character array accTitle, character array accType, float
variable balance. All data members should be in private scope.

Step 2:
Define default constructor in public scope which initializes the data member balance to zero.
Refer Activity 1 code

Step 3:
Define parameterized constructor with parameters character array accTitle, character array
accType. Overloaded constructor should be in public scope.

Hint: Signature of constructor will be.


Accounts(char* _accTitle , char* _accType)

Refer Activity 1 code


Initialize the balance data member with 500.

Step 4:
Define setters and getters for each data member in public scope.

Step 5:
Define the main functions.
Declare one dimensional array of size 10 with data type Accounts.
Hint: Accounts acc[10];

Department of Electrical Engineering 53


Step 6:
This step is very important and need high attention.
You need to define a menu which should have following options.

Press 1 to create new account.


Press 2 to display account info.
Press 3 to deposit amount.
Press 4 to withdraw amount.
Press 5 to check balance.
Press 6 to Exit
After defining the menu get the choice (declare an int type choice variable) from user and define
switch and cases to handle each option.
You need to define cases for each option including default case
Your program should keep asking for choice until user select option 6.

If user enters input other than given option then program should display “wrong input” and then
display menu again.
Hint: use switch-case and do-while to achieve this task.
After defining all cases with proper syntax, perform the next step.

Step 7:
In the first case, you need to define logic for the creation of new account.
You have already declared an array of size 10 with data type Accounts.

Step 8:
In the second case, you need to define the logic to print the account information.
Don’t print information of all accounts.
You need to get account number as input from user and then print the information of that account.

Step 9:
In the third case, you need to define the logic to perform the deposit amount operation.
You need to get account number from user and then get amount to be deposit.

Department of Electrical Engineering 54


Step 10:
In the fourth case, you need to define the logic to perform withdraw operation.
You need to get the account number from user and then get amount to be withdraw.

Step 11:
In fifth case, you need to define the logic to perform check balance operation.
You need to get account number from user and then display the balance on console.

Department of Electrical Engineering 55


Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering 56


Student’s Signature: ________________ Date: ________________

Department of Electrical Engineering 57


LABORATORY SKILLS ASSESSMENT (Psychomotor)
Total Marks: 100

Criteria Level 1 Level 2 Level 3 Level 4


Score (S)
(Max Marks) 0% ≤ S < 50% 50% ≤ S< 70% 70% ≤ S< 90% 90%≤ S ≤100%
Procedural Selects Selects and applies Selects and applies Selects and applies
Awareness inappropriate appropriate skills the appropriate appropriate
(20) skills and/or and/or strategies strategies and/or strategies and/or
strategies required by the task skills specific to the skills specific to
required by the with some errors task without the task without
task significant errors any error

Program Logic Program logic Program logic has Program logic is Program logic is
(20) has many errors some errors with mostly correct, but correct, with no
with majority of some contradictory may contain known errors, and
contradictory conditions occasional errors or no redundant
conditions redundant/ or contradictory
contradictory conditions.
conditions
Practical Makes several Makes few critical Makes some non- Applies the
Implementation critical errors in errors in applying critical errors in procedural
(30) applying procedural applying procedural knowledge in
procedural knowledge knowledge perfect ways
knowledge
Program Program does not Program approaches Program produces Program produces
Correctness produce correct answers or correct answers or correct answers or
(20) correct answers appropriate results appropriate results appropriate results
or appropriate for most inputs, but for most inputs. for all inputs
results for can contain tested.
most inputs. miscalculations in
some cases.
Use of Software Uses software Uses software tool, Uses software tool, Uses software tool,
Tool tool, with with some with considerable with a high degree
(10) limited competence competence of competence
competence

Marks Obtained

Instructor’s Signature: ________________ Date: ________________

Department of Electrical Engineering 58


LABORATORY SKILLS ASSESSMENT (Affective)

Total Marks: 40

Criteria Level 1 Level 2 Level 3 Level 4


Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained
LABORATORY SKILLS ASSESSMENT (Cognitive)

Total Marks: 10
( If any )
Marks Obtained

Instructor’s Signature: ________________ Date: ________________

Department of Electrical Engineering 59

You might also like