object oriented programming c++

113

Click here to load reader

Upload: fawadkhan

Post on 14-Dec-2015

103 views

Category:

Documents


21 download

DESCRIPTION

Lab Manual

TRANSCRIPT

Page 1: Object Oriented Programming C++

Programming for Engineers II Lab EL-112

Lab Outline

Labs Topic

Lab 1 Review of C++ Language Programming Basics

Lab 2 Structures

Structures

Operations on structures

Initializing structure Members

Structures within Structures

Lab 3 Structures

Structure Variables and Functions

Passing Structures by Reference

Returning Structure Variables

Array with Structure Variables

Enum

Lab 4 Introduction to Classes and Objects

Classes, its Objects and members

Accessing members functions

Constructors

Lab 5 Class in a separate file for Reusability

A Header containing a user defined class

Scope Resolution Operator ::

A Header containing only class member functions

prototypes (not Definition’s)

Note for users using compliers

Lab 6 Classes a Deeper Look (1)

Member Access Operators

Class Scope (Static Member Variables)

Utility Function (Helper Function)

Constructors with Default Arguments

Lab 7 Classes a Deeper Look (2)

Destructors

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 2: Object Oriented Programming C++

When Constructors and Destructors are called?

Memberwise Assignment Operator

Returning Reference to a Private Data Member

Lab 8 Classes a Deeper Look (3)

const (Constant) Objects and const Member

Functions

Composition: Objects as Members of Classes

Lab 9 Classes a Deeper Look (4)

friend Functions and friend Classes

Proxy Classes

Lab 10 File Processing

Lab 11 Operator Overloading

Lab 12 OOP: Inheritance

Lab 13 OOP: Polymorphism

Lab 14 Exception Handling

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 3: Object Oriented Programming C++

Review of C Language Programming Basics

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 1

Review of C Language Programming Basics

If

if ( condition is TRUE ) Execute the next statement

If/else

if ( condition is TRUE ) { Execute these statements } else if ( another condition is TRUE ) { Execute these statements } else (condition is FALSE) { Execute these statements }

Switch

switch ( variable ) { case this-value: Code to execute if <variable> == this-value break; case that-value: Code to execute if <variable> == that-value break; ... default: Code to execute if <variable> does not equal the value following any of the cases break; }

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 4: Object Oriented Programming C++

Review of C Language Programming Basics

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

For

for ( variable initialization; condition; variable update ) { Code to execute while the condition is true }

While

while ( condition ) {Code to execute while the condition is true}

Do while

do { } while (condition);

Functions

Function Definition: return-type function_name ( arg_type arg1, ..., arg_type argN ); { …. } Function Prototype: return-type function_name (arg_type, … ,arg_type); Function Calling: function_name ( values passed1,… values passedN )

Arrays

int one_dimensional_array[size of row]; int two_dimensional_array[size of row] [size of col];

Pointers

int x; /* A normal integer*/ int *p; /* A pointer to an integer ("*p" is an integer, so p must be a pointer to an integer) */ p = &x; /* Read it, "assign the address of x to p" */

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 5: Object Oriented Programming C++

Review of C Language Programming Basics

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

Q.1 Write a program to check whether the entered character is upper case or lower case using

if/else statement.

Output

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 6: Object Oriented Programming C++

Review of C Language Programming Basics

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

Q.2 Write a program using switch statement to convert from

1 Degree centigrade to degree Fahrenheit when “f” is entered

2 Degree Fahrenheit to degree centigrade when “c” is entered

Output

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 7: Object Oriented Programming C++

Review of C Language Programming Basics

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

Q.3 Find the factorial of any entered value until 0 (zero) value character is entered.

Output

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 8: Object Oriented Programming C++

Review of C Language Programming Basics

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

Q.4 Write a C program that prints below shape using nested loop

*

***

*****

*******

*********

*******

*****

***

*

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 9: Object Oriented Programming C++

Review of C Language Programming Basics

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

Q.5 Write a code to find the Transpose of 4x4 square matrix / array.

Output

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 10: Object Oriented Programming C++

Review of C Language Programming Basics

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

Q.6 Write a program that prints the values from an array using pointer variable. The array is

given below int y [4] = {6,12,3,10}

Output

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 11: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 2

Structures

Structures

Operations on structures

Initializing structure Members

Structures within Structures

Structures

A structure is a collection of simple variables. The variables in a structure can be

of different types. Some can be integer; some can be float, and so on. The data

items in a structure are called the members of the structure.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 12: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

CODE

#include <iostream>

#include <conio.h>

using namespace std;

struct part

{

int modelnumber;

int partnumber;

float cost;

};

void main()

{

part part1;

part1.modelnumber = 6244;

part1.partnumber = 373;

part1.cost = 217.55F;

cout << "Model " << part1.modelnumber;

cout << ", part " << part1.partnumber;

cout << ", costs $" << part1.cost << endl;

}

OUTPUT

Model 6244, part 373, costs $217.55

Operations on Structures

Structures work with assignment operator (=). One structure variable can be

assigned to another only when they are of the same structure type. Like for

structure card with structure variables temp, chosen, prize, card1, card2,

card3. So we can use assignments like temp = card3; card3 = card1; card1 =

temp;

The „+„operator does not with types we define ourselves, like structure

Distance with variables like d1, d2, d3. Notice that we can‟t add the two

distances with a program statement like d3 = d1 + d2;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 13: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

Structures can’t be compared. Like for structure card with structure variables

temp, chosen, prize, card1, card2, card3. You can‟t say if (chosen == prize)

//not legal yet

Addition problem can be solved with operator overloading. (To be discussed in

later labs)

Initializing Structure Members

Dot operator is member access operator for example: part1.modelnumber = 6244;

CODE

#include <iostream>

#include <string>

using namespace std;

struct spec{

int model;

string name;

float cost;

};

int main()

{

spec a1, a2, a3, a4;

cout << "name: "; getline(cin, a1.name); //cin >> a1.name;

cout << "model: "; cin >> a1.model;

cout << "cost: "; cin >> a1.cost;

a2 = { 21, "nokia siemens", 34 }; //initialize here like spec a2 = {} if error

a3 = a2;

a4.model = 61;

a4.name = "sony ericson";

a4.cost = 37;

cout << endl;

cout << a1.name << endl;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 14: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

cout << a1.cost << endl;

cout << a1.model << endl;

cout << endl;

cout << a2.name << endl;

cout << a2.cost << endl;

cout << a2.model << endl;

cout << endl;

cout << a3.name << endl;

cout << a3.cost << endl;

cout << a3.model << endl;

cout << endl;

cout << a4.name << endl;

cout << a4.cost << endl;

cout << a4.model << endl;

return 0;

}

OUTPUT

name: motorola x7

model: 45

cost: 78

motorola x7

78

45

nokia siemens

34

21

nokia siemens

34

21

sony ericson

37

61

Faw

ad Khan

For Dem

onstra

tion P

urpose

s

Only

Page 15: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

Structures within Structures

We must apply the dot operator twice to access the structure members for example:

dining.length.feet = 13;

Room dining = { {13, 6.5}, {10, 0.0} };

CODE

#include <iostream>

#include <conio.h>

using namespace std;

struct Distance

{

int feet;

float inches;

};

struct Room

{

Distance length;

Distance width;

};

void main()

{

Room dining; //define a room

dining.length.feet = 13; //assign values to room

dining.length.inches = 6.5;

dining.width.feet = 10;

dining.width.inches = 0.0;

//Alternative: Room dining = { {13, 6.5}, {10, 0.0} };

//convert length & width

float l = dining.length.feet + dining.length.inches / 12;

float w = dining.width.feet + dining.width.inches / 12;

//find area and display it

cout << "Dining room area is " << l * w << " square feet\n";

_getch();

}

OUTPUT

Dining room area is 135.417 square feet

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 16: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

Lab Tasks:

Q1: Write a structure for a product containing its members names as string name,

int ID, float Price, int prod_no and string company. Define three variables for the

structure and assign first variable in program as prod1 = {“Dura cell”, 34, 24.56,

1001, “Mitsubishi”}; and the 2nd

variable is assigned on runtime. The third variable

should be assigned the same data as of variable two. Finally the program will

display the data of all the structure variables.

Your output should appear like this.

enter prod2 spec

name titan watch

ID 56

price 999

prod_no 101

company Titan

Product1 Spec:

name Dura cell

ID 34

Price 24.56

Price 1001

company Mitsubishi

Product2 Spec:

name titan watch

ID 56

Price 999

Price 101

company Titan

Product3 Spec:

name titan watch

ID 56

Price 999

Price 101

company Titan

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 17: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

Q2: Write a structure named student containing the three members as subject1,

subject2 and subject3. The program should evaluate the average of 3 subjects of 4

individual student variables and display against each student his grade depending

on the average. If

Avg > 90 display “A”

Avg > 80 and Avg<89 display “B”

Avg > 70 and Avg<79 display “C”

Avg < 60 display “F”

Your output should appear like this.

Name1 fawad

Name2 kashif

Name3 bilal

student 1 credentials

sub1 89

sub2 78

sub3 68

student 2 credentials

sub1 43

sub2 56

sub3 90

student 3 credentials

sub1 98

sub2 78

sub3 99

Name Avg Grade

fawad 78 Grade C

kashif 63 Grade F

bilal 91 Grade A

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 18: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

Q3: Write a structure to declare a complex number which has 2 members complex

and imaginary. Write a program to add, subtract and multiply 2 complex numbers.

Your output should appear as

Your output should appear like this.

Press 1 to add two complex numbers.

Press 2 to subtract two complex numbers.

Press 3 to multiply two complex numbers.

Press 4 to exit.

Enter your choice

1

Enter a and b where a + ib is the first complex number.

a = 2

b = 3

Enter c and d where c + id is the second complex number.

c = 4

d = 2

Sum of two complex numbers = 6+5i

Press any key to enter choice again...

Press 1 to add two complex numbers.

Press 2 to subtract two complex numbers.

Press 3 to multiply two complex numbers.

Press 4 to exit.

Enter your choice

2

Enter a and b where a + ib is the first complex number.

a = 2

b = 3

Enter c and d where c + id is the second complex number.

c = 4

d = 2

Difference of two complex numbers = -2+1i

Press any key to enter choice again...

Press 1 to add two complex numbers.

Press 2 to subtract two complex numbers.

Press 3 to multiply two complex numbers.

Press 4 to exit.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 19: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 9

Enter your choice

3

Enter a and b where a + ib is the first complex number.

a = 2

b = 3

Enter c and d where c + id is the second complex number.

c = 4

d = 2

Multiplication of two complex numbers =2+16i

Press any key to enter choice again...

Press 1 to add two complex numbers.

Press 2 to subtract two complex numbers.

Press 3 to multiply two complex numbers.

Press 4 to exit.

Enter your choice

4

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 20: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 3

Structures

Structure Variables and Functions

Passing Structures by Reference

Returning Structure Variables

Array with Structure Variables

Enum

struct Variables and Functions

A struct variable can be passed as a parameter either by value or by reference and a

function can return a value of type struct.

#include <iostream>

using namespace std;

struct student

{

int rollno;

int examScore;

};

void getStudent(student& stu); //passed by reference

void showStudent(student stu); //passed by value

student newStudent();

void main()

{

student stu1, stu2;

getStudent(stu1);

showStudent(stu1);

cout << "\nNow with struct returning function" << endl;

stu2 = newStudent();

showStudent(stu2);

}

void getStudent(student& stu)

{

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 21: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

cout << "Enter Student's Information" << endl;

cout << "Roll No: ";

cin >> stu.rollno;

cout << "Exam Score: ";

cin >> stu.examScore;

}

void showStudent(student stu)

{

cout << "\nStudent's Information" << endl;

cout << "Roll No: " << stu.rollno << endl;

cout << "Exam Score: " << stu.examScore << endl;

}

student newStudent()

{

student std1;

std1.rollno = 123;

std1.examScore = 15;

return std1;

}

OUTPUT

Enter Student's Information

Roll No: 55

Exam Score: 67

Student's Information

Roll No: 55

Exam Score: 67

Now with struct returning function

Student's Information

Roll No: 123

Exam Score: 15

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 22: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

Passing Structures by Reference

#include <iostream>

using namespace std;

struct Distance //English distance

{

int feet;

float inches;

};

void scale(Distance&, float); //passed by reference

void engldisp(Distance); //passed by value

int main()

{

Distance d1 = { 12, 6.5 }; //initialize d1

cout << "d1 = "; engldisp(d1); //display old d1

scale(d1, 0.5); //scale d1

cout << "\nd1 = "; engldisp(d1); //display new d1

return 0;

}

// scales value of type Distance by factor

void scale(Distance& dd, float factor)

{

float inches = (dd.feet * 12 + dd.inches) * factor;

dd.feet = static_cast<int>(inches / 12);

dd.inches = inches - dd.feet * 12;

}

//--------------------------------------------------------------

// engldisp()

// display structure of type Distance in feet and inches

void engldisp(Distance dd) //parameter dd of type Distance

{

cout << dd.feet << "\'-" << dd.inches << endl;

}

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 23: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

OUTPUT

d1 = 12'-6.5

d1 = 6'-3.25

Returning Structure Variables

#include <iostream>

using namespace std;

////////////////////////////////////////////////////////////////

struct Distance //English distance

{

int feet;

float inches;

};

////////////////////////////////////////////////////////////////

Distance addengl(Distance, Distance); //return type structure

void engldisp(Distance);

int main()

{

Distance d3; //define three lengths

//get length d1 from user

Distance d1 = { 6, 7 };

Distance d2 = { 10, 4 };

d3 = addengl(d1, d2); //d3 is sum of d1 and d2

cout << endl;

engldisp(d1); cout << " + "; //display all lengths

engldisp(d2); cout << " = ";

engldisp(d3); cout << endl;

return 0;

}

//--------------------------------------------------------------

// addengl()

// adds two structures of type Distance, returns sum

Distance addengl(Distance dd1, Distance dd2)

{

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 24: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

Distance dd3; //define a new structure for sum

dd3.inches = dd1.inches + dd2.inches; //add the inches

dd3.feet = dd1.feet + dd2.feet; //add the feet

return dd3; //return structure

}

// display structure of type Distance in feet and inches

void engldisp(Distance dd)

{

cout << dd.feet << "\'-" << dd.inches << "\"";

}

OUTPUT

6'-7" + 10'-4" = 16'-11"

Array with Structure Variables

#include <iostream>

#include <string>

using namespace std;

struct Item{

string name;

int id;

};

int main()

{

Item prod[3]; //basically defining four variables of structure here

for (int i = 0; i<3; i++)

{

cout << endl;

cout << "enter values for item" << 1 + i << endl;

cout << "name " << 1 + i << " ";

getline(cin, prod[i].name);

cout << "id " << 1 + i << " ";

cin >> prod[i].id;

cin.get();

}

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 25: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

cout << endl;

cout << " item " << " " << "name" << " " << "id" << endl;

for (int i = 0; i < 3; i++)

{

cout << " item " << i + 1 << " " << prod[i].name << " " << prod[i].id

<< endl;

}

return 0;

}

OUTPUT

enter values for item1

name 1 kyoceria

id 1 1001

enter values for item2

name 2 Nikon

id 2 101

enter values for item3

name 3 Canon

id 3 707

item name id

item 1 kyoceria 1001

item 2 Nikon 101

item 3 Canon 707

Enum

An enumeration is a list of all possible values.

In Enum you must give a specific name to every possible value.

You can use the standard arithmetic operators on enum types.

Enumerations are treated internally as integers.

First name in the list is given the value 0; the next name is given the value

1, and so on.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 26: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

Ordering can be altered by using an equal sign to specify a starting point

other than 0. For example, if you want the suits to start with 1 instead of 0,

you can say enum Suit { clubs=1, diamonds, hearts, spades };

#include <iostream>

using namespace std;

//specify enum type

enum days_of_week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

int main()

{

days_of_week day1, day2; //define variables

day1 = Mon; //give values to

day2 = Thu; //variables

int diff = day2 - day1; //can do integer arithmetic

cout << "Days between = " << diff << endl;

if (day1 < day2) //can do comparisons

cout << "day1 comes before day2\n";

return 0;

}

OUTPUT

Days between = 3

day1 comes before day2

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 27: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

Lab Tasks:

Q1: Write a structure with structure name book and its 4 members as string course

name in which you read that particular book, string book name, string author

name (book author) and int semester in which your read that book. The variable of

structure should be defined as univ[5]. Now the structure has 5 variables for

holding the record of 5 books which you have read till now in your engineering.

The structure has 2 function’s namely input_record and print to input data to

structure and displaying values stored in structure. The functions prototypes are

shown below.

void input_record(book aa[], int n);

void print(book bb[], int n);

Your Output should appear as:

enter book info

course name prog for engineers

book name computer prog

author name dietel

semester number 2

enter book info

course name microprocessor

book name intro to controllers

author name mazidi

semester number 5

enter book info

course name signals and systems

book name signals and system

author name william sky

semester number 5

enter book info

course name EMT

book name electromagnetic theory

author name john

semester number 4

enter book info

course name Differential Equations

book name Intro to differential

author name kryzgic

semester number 1

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 28: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 9

S# course book author semester

1 prog for engineers computer prog dietel 2

2 microprocessor intro to controllers mazidi 5

3 signals and systems signals and system william sky 5

4 EMT electromagnetic theory john 4

5 Differential Equations Intro to differential kryzgic 1

Q2: Write a structure for salesman sales in 3 months. The structure has 4 members.

First one of type string to name employee and other 3 are of type integer for sales

of 3 months. Define 2 variables for salesman. 3 functions are used. 1st to input

record, 2nd

to evaluate individual sales of each employee in all 3 months and 3rd

for

evaluating the sales of company in individual months. Function prototypes are

given.

void input_record(saleman& ss);

int i_sales(saleman ss);

saleman c_sales(saleman aa, saleman bb);

Your Output should appear as:

Enter Saleman Sales enter saleman name ali jan sales in Rs 45 feb sales in Rs 4000 march sales in Rs 6660 enter saleman name arif jan sales in Rs 7000 feb sales in Rs 4503 march sales in Rs 456 Individual Saleman Commulative Sale Name Commulative Sale ali 10705 arif 11959 Individual Month Commulative Sale

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 29: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 10

Jan Feb Mar 7045 8503 7116

Q3: Write a structure named student containing the three members as

subject1, subject2 and subject3 and one member name to input student name.

Define an array type variable named stud[5] and input record of 5 students. Three

functions are used.

get_data: To input data to structure

print_average: To display the class average of each subject

print_grade: To return the class average grade and print the grade from main

function

If

Avg > 90 display “A”

Avg > 80 and Avg<89 display “B”

Avg > 70 and Avg<79 display “C”

Avg < 60 display “F”

Your Output should appear as:

Enter Student Record Name1 ali sub1 56 sub2 7 sub3 89 Name2 salman sub1 87 sub2 80 sub3 98 Name3 sana sub1 87 sub2 54 sub3 09 Name4 ghazi sub1 12 sub2 49 sub3 90

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 30: Object Oriented Programming C++

Structures

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 11

Name5 uzma sub1 98 sub2 67 sub3 56 class_avg_sub1 68 class_avg_sub2 51 class_avg_sub3 68 Subject 1 Grade F Subject 2 Grade F Subject 2 Grade F

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 31: Object Oriented Programming C++

Introduction to Classes and Objects

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 4

Introduction to Classes and Objects

Classes, its Objects and members

Accessing members functions

Constructors

Classes, its Objects and members

Class is specifically designed to group data and functions.

Object combines data and the operations on that data in a single unit.

The components of a class are called the members of the class.

In the definition of the class, you cannot initialize a variable when you

declare it.

The members of a class are classified into three categories: private, public,

and protected.

Following are some facts about public and private members of a class:

a. By default, all members of a class are private.

b. If a member of a class is private, you cannot access it outside of the

class.

c. A public member is accessible outside of the class.

d. To make a member of a class public, you use the member access

specifier public:

class clockType

{

private:

int hr;

int min;

int sec;

public:

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 32: Object Oriented Programming C++

Introduction to Classes and Objects

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

void setTime(int hours, int minutes, int seconds)

{

}

void getTime(int& hours, int& minutes, int& seconds) const

{

}

void printTime()const

{

}

};

Accessing members functions

Dot operator used for member access. classObjectName.memberName

The word const at the end of the member function getTime specifies that

these functions cannot modify the member variables of a variable of type

clockType.

If the object is declared in the definition of a member function of the class,

then the object can access both the public and private members.

If the object is declared elsewhere (for example, in a user’s program), then

the object can access only the public members of the class. The objects

myClock and yourClock can access only public members of the class

therefore; private members cannot be accessed by the objects myClock and

yourClock:

myClock.hr=10; //illegal

myClock.min=yourClock.min; //illegal

Member function of a class can call other member functions of the class.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 33: Object Oriented Programming C++

Introduction to Classes and Objects

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

Constructors

The name of a constructor is the same as the name of the class.

A class can have more than one constructor. However, all constructors of a

class have the same name.

Constructors execute automatically when a class object enters its scope.

Which constructor executes depends on the types of values passed to the

class object when the class object is declared.

clockType myClock; // default constructor execute automatically

clockType yourClock(12,3,45);

clockType() //default constructor

{

hr = 0;

min = 0;

sec = 0;

}

clockType(int hours, int minutes, int seconds)

{

setTime(hours, minutes, seconds);

}

CODE

#include<iostream>

using namespace std;

class clockType

{

private:

int hr;

int min;

int sec;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 34: Object Oriented Programming C++

Introduction to Classes and Objects

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

public:

void setTime(int hours, int minutes, int seconds)

{

if (0 <= hours && hours<24)

hr = hours;

else

hr = 0;

if (0 <= minutes && minutes<60)

min = minutes;

else

min = 0;

if (0 <= seconds && seconds<60)

sec = seconds;

else

sec = 0;

}

void getTime(int& hours, int& minutes, int& seconds) const

{

hours = hr;

minutes = min;

seconds = sec;

}

void printTime()const

{

if (hr<10)

cout << "0";

cout << hr << ":";

if (min<10)

cout << "0";

cout << min << ":";

if (sec<10)

cout << "0";

cout << sec;

}

};

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 35: Object Oriented Programming C++

Introduction to Classes and Objects

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

int main(){

int hours = 0, minutes = 0, seconds = 0;

clockType myClock;

clockType yourClock;

myClock.setTime(5, 4, 30);

cout << "myClock: ";

myClock.printTime();

cout << endl;

cout << endl;

cout << "yourClock: ";

yourClock.printTime();

cout << endl;

cout << endl;

yourClock.setTime(5, 45, 16);

cout << "After setting, yourClock: ";

yourClock.printTime();

cout << endl;

cout << endl;

cout << "hours=" << hours << ",minutes=" << minutes << ",seconds=" <<

seconds << endl;

cout << endl;

myClock.getTime(hours, minutes, seconds);

cout << "hours=" << hours << ",minutes=" << minutes << ",seconds=" <<

seconds << endl;

cout << endl;

return 0;

}

OUTPUT

myClock: 05:04:30

yourClock: 0-858993460:0-858993460:0-858993460

After setting, yourClock: 05:45:16

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 36: Object Oriented Programming C++

Introduction to Classes and Objects

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

hours=0,minutes=0,seconds=0

hours=5,minutes=4,seconds=30

If default constructor is defined in Class definition then output will appear like

OUTPUT

myClock: 05:04:30

yourClock: 00:00:00

After setting, yourClock: 05:45:16

hours=0,minutes=0,seconds=0

hours=5,minutes=4,seconds=30

Lab Tasks:

Q1: Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay

a 2 cent toll. Mostly they do, but sometimes a car goes by without paying. The

tollbooth keeps track of the number of cars that have gone by, and of the total

amount of money collected. Model this tollbooth with a class called tollBooth. The

two data items are a type unsigned int to hold the total number of cars, and a type

double to hold the total amount of money collected. A constructor initializes both

of these to 0. A member function called payingCar() increments the car total and

adds 2 to the cash total. Another function, called nopayCar(), increments the car

total but adds nothing to the cash total. Finally, a member function called display()

displays the totals. Make appropriate member functions const. Include a program

to test this class. This program should allow the user to push one key (p) to count a

paying car, and another to count a nonpaying car (n). Pushing the (d) key should

cause the program to print out the total cars and total cash and then exit.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 37: Object Oriented Programming C++

Introduction to Classes and Objects

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

Your Output should appear as:

enter a key (p) for paid, (n) for not paid, (d) for exit p

enter a key (p) for paid, (n) for not paid, (d) for exit n

enter a key (p) for paid, (n) for not paid, (d) for exit p

enter a key (p) for paid, (n) for not paid, (d) for exit p

enter a key (p) for paid, (n) for not paid, (d) for exit n

enter a key (p) for paid, (n) for not paid, (d) for exit p

enter a key (p) for paid, (n) for not paid, (d) for exit p

enter a key (p) for paid, (n) for not paid, (d) for exit n

enter a key (p) for paid, (n) for not paid, (d) for exit n

enter a key (p) for paid, (n) for not paid, (d) for exit p

enter a key (p) for paid, (n) for not paid, (d) for exit p

enter a key (p) for paid, (n) for not paid, (d) for exit n

enter a key (p) for paid, (n) for not paid, (d) for exit d

total cars 12

toll paid 14

Q2: Create a class called shape. Use this class to store two int type values that

could be used to compute the area of figures i-e of a rectangle and triangle. Define

members function as

Setvalues…used to set the values of variables

Getvalues…used to get the values of variables

area_r…used to determine the area of rectangle

area_t…used to determine the area of triangle

shape()…default constructor used to set the values of variables to 0 on object

creation.

Define the logic in main function so as to calculate the area until “E” is typed. If

“E” is typed the program should exit.

"Enter your choice (T) for Triangle and (R) for Rectangle and (E) to Exit”

If any of the choice is entered, let say (T) then function Setvalues is called to input

values of variables. After then area_t is called to evaluate area of triangle. Then

use the function getvalues to get the input values and store in dummy variables m,

n in main function. Finally call disp(m, n, a) function to display results, where a

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 38: Object Oriented Programming C++

Introduction to Classes and Objects

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

corresponds to area. Disp function is a not a class member function. It a function

other than class member functions in order to display results.

Area of triangle = (a*b)/2

Area of rectangle = (a*b)

Your Output should appear as:

Enter your choice (T) for Triangle and (R) for Rectangle and (E) to Exit

T

Enter Value for x 6

Enter Value for y 7

Triangle

Values entered are 6 and 7

Area is 21

Enter your choice (T) for Triangle and (R) for Rectangle and (E) to Exit

R

Enter Value for x 7

Enter Value for y 6

Rectangle

Values entered are 7 and 6

Area is 42

Enter your choice (T) for Triangle and (R) for Rectangle and (E) to Exit

E

Exiting

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 39: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 5

Class in a separate file for Reusability

A Header containing a user defined class

Scope Resolution Operator ::

A Header containing only class member functions prototypes (not Definition’s)

Note for users using compliers

A Header containing a user defined class

Save as Class_Name .h

#include<iostream>

using namespace std;

class clockType

{

private:

int hr;

int min;

int sec;

public:

void setTime(int hours, int minutes, int seconds)

{

if (0 <= hours && hours<24)

hr = hours;

else

hr = 0;

if (0 <= minutes && minutes<60)

min = minutes;

else

min = 0;

if (0 <= seconds && seconds<60)

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 40: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

sec = seconds;

else

sec = 0;

}

void getTime(int& hours, int& minutes, int& seconds) const

{

hours = hr;

minutes = min;

seconds = sec;

}

void printTime()const

{

if (hr<10)

cout << "0";

cout << hr << ":";

if (min<10)

cout << "0";

cout << min << ":";

if (sec<10)

cout << "0";

cout << sec;

}

};

Save as File_Name.cpp

# include "clockType.h"

int main(){

int hours = 0, minutes = 0, seconds = 0;

clockType myClock;

clockType yourClock;

myClock.setTime(5, 4, 30);

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 41: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

cout << "myClock: ";

myClock.printTime();

cout << endl;

cout << endl;

cout << "yourClock: ";

yourClock.printTime();

cout << endl;

cout << endl;

yourClock.setTime(5, 45, 16);

cout << "After setting, yourClock: ";

yourClock.printTime();

cout << endl;

cout << endl;

cout << "hours=" << hours << ",minutes=" << minutes << ",seconds=" <<

seconds << endl;

cout << endl;

myClock.getTime(hours, minutes, seconds);

cout << "hours=" << hours << ",minutes=" << minutes << ",seconds=" <<

seconds << endl;

cout << endl;

return 0;

}

Scope Resolution Operator ::

If the function definitions are not defined in the class instead only the function

prototypes are given. So scope resolution operator is used to access and link the

function prototypes with function definitions.

return type function_name (type parameters,…); // prototype

return type class_name:: function_name (type parameters,…) //definition

{

}

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 42: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

A Header containing only class member functions prototypes (not Definitons)

Save as Class_Name .h

#include <iostream>

using namespace std;

class clockType

{

private:

int hr;

int min;

int sec;

public:

void setTime(int hours, int minutes, int seconds);

void getTime(int& hours, int& minutes, int& seconds) const;

void printTime()const;

};

Save as Class_Name .cpp

#include "clockType.h"

void clockType::setTime(int hours, int minutes, int seconds)

{

if (0 <= hours && hours<24)

hr = hours;

else

hr = 0;

if (0 <= minutes && minutes<60)

min = minutes;

else

min = 0;

if (0 <= seconds && seconds<60)

sec = seconds;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 43: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

else

sec = 0;

}

void clockType::getTime(int& hours, int& minutes, int& seconds) const

{

hours = hr;

minutes = min;

seconds = sec;

}

void clockType::printTime()const

{

if (hr<10)

cout << "0";

cout << hr << ":";

if (min<10)

cout << "0";

cout << min << ":";

if (sec<10)

cout << "0";

cout << sec;

}

Save as File_Name.cpp

# include "clockType.h"

int main(){

int hours = 0, minutes = 0, seconds = 0;

clockType myClock;

clockType yourClock;

myClock.setTime(5, 4, 30);

cout << "myClock: ";

myClock.printTime();

cout << endl;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 44: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

cout << endl;

cout << "yourClock: ";

yourClock.printTime();

cout << endl;

cout << endl;

yourClock.setTime(5, 45, 16);

cout << "After setting, yourClock: ";

yourClock.printTime();

cout << endl;

cout << endl;

cout << "hours=" << hours << ",minutes=" << minutes << ",seconds=" <<

seconds << endl;

cout << endl;

myClock.getTime(hours, minutes, seconds);

cout << "hours=" << hours << ",minutes=" << minutes << ",seconds=" <<

seconds << endl;

cout << endl;

return 0;

}

Note for users using compliers

For Visual Studio users you need to call Class_Name .h in main.cpp

For Dev.cpp users you need to call Class_Name .cpp in main.cpp

Lab Tasks:

Q1: Create a class called shape using a Header containing only class member

functions prototypes (not Definition’s). Store your program in 3 separate files

named as

Class_Name .h Class definition only function prototypes

Class_Name .cpp Class member functions definitions

File_Name.cpp Main program for operation

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 45: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

Use this class to store two int type values that could be used to compute the area of

figures i-e of a rectangle and triangle. Define members function as

Setvalues…used to set the values of variables

Getvalues…used to get the values of variables

area_r…used to determine the area of rectangle

area_t…used to determine the area of triangle

shape()…default constructor used to set the values of variables to 0 on object

creation.

Define the logic in main function so as to calculate the area until “E” is typed. If

“E” is typed the program should exit.

"Enter your choice (T) for Triangle and (R) for Rectangle and (E) to Exit”

If any of the choice is entered, let say (T) then function Setvalues is called to input

values of variables. After then area_t is called to evaluate area of triangle. Then

use the function getvalues to get the input values and store in dummy variables m,

n in main function. Finally call disp(m, n, a) function to display results, where a

corresponds to area. Disp function is a not a class member function. It a function

other than class member functions in order to display results.

Area of triangle = (a*b)/2

Area of rectangle = (a*b)

Your Output should appear as:

Enter your choice (T) for Triangle and (R) for Rectangle and (E) to Exit

T

Enter Value for x 6

Enter Value for y 7

Triangle

Values entered are 6 and 7

Area is 21

Enter your choice (T) for Triangle and (R) for Rectangle and (E) to Exit

R

Enter Value for x 7

Enter Value for y 6

Rectangle

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 46: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

Values entered are 7 and 6

Area is 42

Enter your choice (T) for Triangle and (R) for Rectangle and (E) to Exit

E

Exiting

Q2: Create an Account class that a bank might use to represent customers’ bank

accounts. Include a data member of type int to represent the account balance.

Provide a constructor that receives an initial balance and uses it to initialize the

data member. The constructor should validate the initial balance to ensure that it’s

greater than or equal to 0. If not, set the balance to 0 and display an error message

indicating that the initial balance was invalid. Provide three member functions.

Member function credit should add an amount to the current balance, also

displaying the actual amount (previously in account) and final amount (amount in

account now). Member function debit should withdraw money from the Account

and ensure that the debit amount does not exceed the Account’s balance. If it does,

the balance should be left unchanged and the function should print a message

indicating "Debit amount exceeded account balance." Else it would display the

actual amount (previously in account) and final amount after withdrawal (amount

in account now). Member function getBalance should return the current balance.

Create a program that creates two Account objects and tests the member functions

of class Account.

Your Output should appear as:

initial balance was invalid

initial balance was invalid

User 1 Account

Account Balance 0

Enter Amount to be deposited 50000

Origional Amount 0

Total Amount 50000

Enter Amount withdrawal 3000

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 47: Object Oriented Programming C++

Class in a separate file for Reusability

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 9

Origional Amount 50000

Total Amount 47000

Account Balance 47000

User 2 Account

Account Balance 0

Enter Amount to be deposited 27000

Origional Amount 0

Total Amount 27000

Enter Amount withdrawal 5000

Origional Amount 27000

Total Amount 22000

Account Balance 22000

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 48: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 6

Classes a Deeper Look (1)

Member Access Operators

Class Scope (Static Member Variables)

Utility Function (Helper Function)

Constructors with Default Arguments

Member Access Operators

The dot member selection operator (.) is preceded by an object’s name or

with a reference to an object to access the object’s members.

The arrow member selection operator (->) is preceded by a pointer to an

object to access the object’s members.

CODE

#include <iostream>

using namespace std;

// class Count definition

class Count

{

public: // public data is dangerous

// sets the value of private data member x

void setX(int value)

{

x = value;

} // end function setX

// prints the value of private data member x

void print()

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 49: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

{

cout << x << endl;

} // end function print

private:

int x;

}; // end class Count

int main()

{

Count counter; // create counter object

Count *counterPtr = &counter; // create pointer to counter

Count &counterRef = counter; // create reference to counter

cout << "Set x to 1 and print using the object's name: ";

counter.setX(1); // set data member x to 1

counter.print(); // call member function print

cout << "Set x to 2 and print using a reference to an object: ";

counterRef.setX(2); // set data member x to 2

counterRef.print(); // call member function print

cout << "Set x to 3 and print using a pointer to an object: ";

counterPtr->setX(3); // set data member x to 3

counterPtr->print(); // call member function print

return 0;

} // end main

OUTPUT

Set x to 1 and print using the object's name: 1

Set x to 2 and print using a reference to an object: 2

Set x to 3 and print using a pointer to an object: 3

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 50: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

Class Scope (Static Member Variables)

Static member function of a class does not need any object to be invoked.

It can be called using the name of the class and the scope resolution

operator.

Only non-static member variables of the class become the member variables

of each object.

Static member variable of a class, C++ allocates only one memory space.

CODE

# include <iostream>

using namespace std;

class illustrate

{

private:

int x;

static int y; //private static variable

public:

static int count; //public static variable

void print()const //Function to output x, y, and count.

{

cout << "x=" << x << ", y=" << y << ", count=" << count << endl;

}

void setX(int a) //Function to set x

{

x = a;

}

static void increment() //Function to increment y by 1.

{

y++;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 51: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

count++;

// x++; //error

}

illustrate(int a,int b,int c) //constructor

{

x = a;

y = b;

count = c;

}

};

int illustrate::count = 0;

int illustrate::y = 0;

int main()

{

illustrate illusObject1(3,5,8);

illustrate illusObject2(78,56,33);

illusObject1.print();

illusObject2.print();

illustrate::increment();

illustrate::count++;

// illustrate::y++; // error

illusObject1.print();

illusObject2.print();

cout << " Increment using " << " illusObject1 " << endl;

illusObject1.increment();

illusObject1.setX(8);

illusObject1.print();

illusObject2.print();

cout << " Increment using " << " illusObject2 " << endl;

illusObject2.increment();

illusObject2.setX(23);

illusObject1.print();

illusObject2.print();

return 0;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 52: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

}

OUTPUT

x=3, y=56, count=33

x=78, y=56, count=33

x=3, y=57, count=35

x=78, y=57, count=35

Increment using illusObject1

x=8, y=58, count=36

x=78, y=58, count=36

Increment using illusObject2

x=8, y=59, count=37

x=23, y=59, count=37

Utility Function (Helper Function)

A private member function that supports the operation of the class’s other

member functions.

Utility functions are not intended to be used by clients of a class rather can

be used by friends of a class.

Constructors with Default Arguments

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 53: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

CODE

#include <iostream>

using namespace std;

class clockType

{

private:

int hr;

int min;

int sec;

void actual_time()const; //helper Function

public:

void setTime(int hours, int minutes, int seconds);

void getTime(int& hours, int& minutes, int& seconds) const;

void printTime()const;

clockType(int = 11, int = 59, int = 59);

};

void clockType::actual_time()const

{

if (hr<10)

cout << "0";

cout << hr << ":";

if (min<10)

cout << "0";

cout << min << ":";

if (sec<10)

cout << "0";

cout << sec;

cout << endl;

}

void clockType::setTime(int hours, int minutes, int seconds)

{

if (0 <= hours && hours<24)

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 54: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

hr = hours;

else

hr = 0;

if (0 <= minutes && minutes<60)

min = minutes;

else

min = 0;

if (0 <= seconds && seconds<60)

sec = seconds;

else

sec = 0;

}

void clockType::getTime(int& hours, int& minutes, int& seconds) const

{

hours = hr;

minutes = min;

seconds = sec;

}

void clockType::printTime()const

{

actual_time(); //helper function

}

clockType::clockType(int hours, int minutes, int seconds)

{

setTime(hours, minutes, seconds);

}

int main(){

int hours = 0, minutes = 0, seconds = 0;

clockType first_Clock(6,12,12);

clockType Second_Clock(5);

clockType Third_Clock;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 55: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

first_Clock.printTime();

Second_Clock.printTime();

Third_Clock.printTime();

first_Clock.setTime(5, 4, 30);

first_Clock.printTime();

cout << endl;

cout << "hours=" << hours << ",minutes=" << minutes << ",seconds=" <<

seconds << endl;

cout << endl;

first_Clock.getTime(hours, minutes, seconds);

cout << "hours=" << hours << ",minutes=" << minutes << ",seconds=" <<

seconds << endl;

cout << endl;

return 0;

}

OUTPUT

06:12:12

05:59:59

11:59:59

05:04:30

hours=0,minutes=0,seconds=0

hours=5,minutes=4,seconds=30

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 56: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 9

Lab Tasks:

Q1: The equation of a line in standard form is ax+by=c, where in both a and b

cannot be zero, and a, b, and c are real numbers. If b!= 0, then –a/b is the slope of

the line. If a=0, then it is a horizontal line, and if b=0, then it is a vertical line. The

slope of a vertical line is undefined. Two lines are parallel if they have the same

slope. Two lines are perpendicular if either one of the lines is horizontal and the

other is vertical or the product of their slopes is –1. Design the class lineType to

store a line. To store a line, you need to store the values of a (coefficient of x), b

(coefficient of y), and c. Your class must contain the following operations.

a. If a line is non-vertical, then determine its slope.

b. Determine if two lines are equal. (Two lines a1x+b1y=c1 and a2x+b2y=c2 are

equal if a1 = a2, b1= b2 and c1= c2 .

c. Determine if two lines are parallel.

d. Determine if two lines are perpendicular.

e. If two lines are neither parallel, nor perpendicular then display that lines are

intersecting.

Add appropriate constructors to initialize variables of lineType. Also write a

program to test your class.

The function prototypes are

void get() // to input the line parameters i-e the values of a, b and c

float slope() // to check whether the line is Non Vertical? evaluate the

slope of the line : display line is vertical so slope is not defined

void check_equal (const lineType& otherline)const // to check whether the

lines have equal lengths or not

void check(float m1, float m2) // to check whether the lines are parallel ,

perpendicular or intersecting

Your Output should appear as:

Line 1 Parameters

Enter Value of a 5

Enter Value of b 69

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 57: Object Oriented Programming C++

Classes a Deeper Look (1)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 10

Enter Value of c 6

Line is Non Vertical : So its slope is defined

Slope of Line is -0.0724638

Line 2 Parameters

Enter Value of a 5

Enter Value of b 69

Enter Value of c 6

Line is Non Vertical : So its slope is defined

Slope of Line is -0.0724638

The Lines are Parallel

The Lines are Equal

Press any key to continue . . .

Line 1 Parameters

Enter Value of a 45

Enter Value of b 3

Enter Value of c 2

Line is Non Vertical : So its slope is defined

Slope of Line is -15

Line 2 Parameters

Enter Value of a 5

Enter Value of b 8

Enter Value of c 2

Line is Non Vertical : So its slope is defined

Slope of Line is -0.625

The Lines are Intersecting

The Lines are NOT Equal

Press any key to continue . . .

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 58: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 7

Classes a Deeper Look (2)

Destructors

When Constructors and Destructors are called?

Memberwise Assignment Operator

Returning Reference to a Private Data Member

Destructors

A class’s destructor is called implicitly when an object is destroyed.

The name of the destructor for a class is the tilde character (~) followed by

the class name.

When Constructors and Destructors are called?

Destructor calls are made in the reverse order of the corresponding

constructor calls.

Constructors are called for objects defined in global scope before any other

function (including main). The corresponding destructors are called when

main terminates.

Constructors and destructors for automatic objects are called each time

execution enters and leaves the scope of the object.

The constructor for a static local object is called only once, when execution

first reaches the point where the object is defined—the corresponding

destructor is called when main terminates or the program calls function exit.

CODE

#include <iostream>

#include <string>

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 59: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

using namespace std;

class CreateAndDestroy

{

public:

// constructor

CreateAndDestroy::CreateAndDestroy(int ID, string messageString)

{

objectID = ID;

message = messageString;

cout << "Object " << objectID << " constructor runs " << message

<< endl;

}

// destructor

CreateAndDestroy::~CreateAndDestroy()

{

// output newline for certain objects; helps readability

cout << (objectID == 1 || objectID == 6 ? "\n" : "");

cout << "Object " << objectID << " destructor runs " << message

<< endl;

}

private:

int objectID; // ID number for object

string message; // message describing object

};

void create(void); // prototype

CreateAndDestroy first(1, "(global before main)"); // global object

int main()

{

cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl;

CreateAndDestroy second(2, "(local automatic in main)");

static CreateAndDestroy third(3, "(local static in main)");

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 60: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

create(); // call function to create objects

cout << "\nMAIN FUNCTION: EXECUTION RESUMES" << endl;

CreateAndDestroy fourth(4, "(local automatic in main)");

cout << "\nMAIN FUNCTION: EXECUTION ENDS" << endl;

return 0;

} // end main

// function to create objects

void create(void)

{

cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl;

CreateAndDestroy fifth(5, "(local automatic in create)");

static CreateAndDestroy sixth(6, "(local static in create)");

CreateAndDestroy seventh(7, "(local automatic in create)");

cout << "\nCREATE FUNCTION: EXECUTION ENDS" << endl;

} // end function create

OUTPUT

Object 1 constructor runs (global before main)

MAIN FUNCTION: EXECUTION BEGINS

Object 2 constructor runs (local automatic in main)

Object 3 constructor runs (local static in main)

CREATE FUNCTION: EXECUTION BEGINS

Object 5 constructor runs (local automatic in create)

Object 6 constructor runs (local static in create)

Object 7 constructor runs (local automatic in create)

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 61: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

CREATE FUNCTION: EXECUTION ENDS

Object 7 destructor runs (local automatic in create)

Object 5 destructor runs (local automatic in create)

MAIN FUNCTION: EXECUTION RESUMES

Object 4 constructor runs (local automatic in main)

MAIN FUNCTION: EXECUTION ENDS

Object 4 destructor runs (local automatic in main)

Object 2 destructor runs (local automatic in main)

Object 6 destructor runs (local static in create)

Object 3 destructor runs (local static in main)

Object 1 destructor runs (global before main)

Memberwise Assignment Operator && Returning Reference to a Private

Data Member

CODE

#include <iostream>

using namespace std;

class clockType

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 62: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

{

private:

int hr;

int min;

int sec;

public:

clockType(int = 11, int = 59, int = 59);

void printTime()const;

int &badSetHour(int); // DANGEROUS reference return

};

clockType::clockType(int hours, int minutes, int seconds)

{

hr = hours;

min = minutes;

sec = seconds;

}

void clockType::printTime()const

{

if (hr<10)

cout << "0";

cout << hr << ":";

if (min<10)

cout << "0";

cout << min << ":";

if (sec<10)

cout << "0";

cout << sec;

cout << endl;

}

int &clockType::badSetHour(int hh)

{

hr = (hh >= 0 && hh < 24) ? hh : 0;

return hr; // DANGEROUS reference return

} // end function badSetHour

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 63: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

int main(){

clockType myclock(12,5,6);

clockType yourclock;

myclock.printTime();

yourclock.printTime();

yourclock = myclock; // member wise assignment

cout << endl;

myclock.printTime();

yourclock.printTime();

clockType t;

int &hourRef = t.badSetHour(20);

cout << "hour before modification: " << hourRef;

hourRef = 30; // use hourRef to set invalid value in object t

cout << "\nhour after modification: ";

t.printTime();

t.badSetHour(12) = 74; // assign another invalid value to hour

t.printTime();

return 0;

}

OUTPUT

12:05:06

11:59:59

12:05:06

12:05:06

hour before modification: 20

hour after modification: 30:59:59

74:59:59

Fawad

Kha

n

For D

emon

stra

tion

Purpo

ses

Onl

y

Page 64: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

Lab Tasks:

Q1: Create a class Rectangle with attributes length and width, each of which

defaults to 1. Provide member functions that calculate the perimeter and the area

of the rectangle. Also provide set and get functions for the length and width

attributes. The set functions should verify that length and width are each floating-

point numbers larger than 0.0 and less than 20.0.

Your Output should appear as:

Lenght 45

Width 23

Values Not in range : Reenter Values

Lenght 23

Width 13

Values Not in range : Reenter Values

Lenght 14

Width 20

Values Not in range : Reenter Values

Lenght 12

Width 15

Values in range

Length 12

Width15

Area 180

Perimeter 54

Q2: Create a class rational which represents a numerical value by integer values

Numerator and Denominator. Include the following member functions.

Constructor with default arguments

get() to input values to class member variables.

hcf to determine the highest common factor of the numerator and denominator

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 65: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

void reduce( int ) that reduces the rational number by eliminating the highest

common factor between the numerator and denominator.

add function to add two rational numbers and display the answer in rational

number format.

Given below is main function to test all functions of the class.

Main Function

int main()

{

int a,b;

// Defining Object and Calling functions

Rational r1;

r1.get();

a= r1.Hcf();

r1.reduce(a);

// Defining Object and Calling functions

Rational r2;

r2.get();

b = r2.Hcf();

r2.reduce(b);

// Defining Object and Calling add function

Rational r3;

r3.add(r1, r2);

return 0;

}

Function Prototypes

Rational();

void get();

int Hcf();

void reduce(int a);

Rational add(Rational a1, Rational a2)

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 66: Object Oriented Programming C++

Classes a Deeper Look (2)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 9

Your Output should appear as:

Numerator 3

Denominator 21

Entered Fraction 3/21

Reduced Fraction 1/7

Numerator 4

Denominator 7

Entered Fraction 4/7

Reduced Fraction 4/7

Fraction Addition 3/21 + 4/7 = 15/21

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 67: Object Oriented Programming C++

Classes a Deeper Look (3)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 8

Classes a Deeper Look (3)

const (Constant) Objects and const Member Functions

Composition: Objects as Members of Classes

const (Constant) Objects and const Member Functions

void clockType::getTime(int& hours, int& minutes, int& seconds) const

{

// clockType Class Name, getTime Class member function

// const here defines that you cant modify the class private member variables

// hr, min, sec are private member variables of class

// hr++; error

hours = hr;

minutes = min;

seconds = sec;

}

void clockType::setTime(const int hours, const int minutes, const int seconds)

{

// clockType Class Name, setTime Class member function

// const here defines that you cant modify the arguments passed to functions

i-e hours, minutes and seconds

// hr, min, sec are private member variables of class

// hours++;

// hours= hr;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 68: Object Oriented Programming C++

Classes a Deeper Look (3)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

hr = hours;

min = minutes;

sec = seconds;

}

Time wakeUp(6, 45, 0); // non-constant object

const Time noon(12, 0, 0); // constant object

Member functions calling objects

OBJECT MEMBER FUNCTION

non-const non-const

const non-const (Error)

non-const const

const const

Composition: Objects as Members of Classes

CODE

# include<iostream>

# include<string>

using namespace std;

class Date

{

private:

int month;

int date;

int year;

public:

Date(int = 1, int = 1, int = 1950);

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 69: Object Oriented Programming C++

Classes a Deeper Look (3)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

void print() const;

};

Date::Date(int a, int b, int c)

{

month = a;

date = b;

year = c;

}

void Date::print() const

{

cout << month << "/" << date << "/" << year<<endl;

}

class Employee

{

private:

string first_name;

string last_name;

Date birthdate;

Date hiredate;

public:

Employee(const string, const string, const Date , const Date );

void print1()const;

};

Employee::Employee(const string aa, const string bb, const Date dateofbirth, const

Date dateofhiring)

{

first_name = aa;

last_name = bb;

birthdate = dateofbirth;

hiredate = dateofhiring;

}

void Employee::print1()const

{

cout << first_name << ", " << last_name<<endl;

birthdate.print();

hiredate.print();

}

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 70: Object Oriented Programming C++

Classes a Deeper Look (3)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

int main()

{

Date birth;

Date hire;

Employee Manager("aaaa", "aaccc", birth, hire);

cout << endl;

Manager.print1();

}

OUTPUT

aaaa, aaccc

1/1/1950

1/1/1950

CODE

int main()

{

Date birth(7,23,2000);

Date hire(2,11,2011);

Employee Manager("aaaa", "aaccc", birth, hire);

cout << endl;

Manager.print1();

}

OUTPUT

aaaa, aaccc

7/23/2000

2/11/2011

Lab Task:

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 71: Object Oriented Programming C++

Classes a Deeper Look (3)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

Q1: Create a SavingsAccount class. Use a static data member to contain the

annualInterestRate for each of the savers. Each member of the class contains a

private data member savingsBalance indicating the amount the saver currently has

on deposit. Provide a calculateMonthlyInterest member function that calculates

the monthly interest by multiplying the balance by annualInterestRate divided

by 12; this interest should be added to savingsBalance . Provide a static member

function modifyInterestRate that sets the static annualInterestRate to a new

value. Write a driver program to test class SavingsAccount. Instantiate two

different savings Account objects, saver1 and saver2, with balances of $2000.00

and $3000.00, respectively. Set annualInterestRate to 3%, then calculate the

monthly interest and print the new balances for each of the savers. Then set the

annualInterestRate to 4% and calculate the next month’s interest and print the new

balances for each of the savers.

Your Output should appear as:

Output monthly balances for one year at .03

Balances: Saver 1 $2000.00 Saver 2 $3000.00

Month 1: Saver 1 $2005.00 Saver 2 $3007.50

Month 2: Saver 1 $2010.01 Saver 2 $3015.02

Month 3: Saver 1 $2015.04 Saver 2 $3022.56

Month 4: Saver 1 $2020.08 Saver 2 $3030.11

Month 5: Saver 1 $2025.13 Saver 2 $3037.69

Month 6: Saver 1 $2030.19 Saver 2 $3045.28

Month 7: Saver 1 $2035.26 Saver 2 $3052.90

Month 8: Saver 1 $2040.35 Saver 2 $3060.53

Month 9: Saver 1 $2045.45 Saver 2 $3068.18

Month 10: Saver 1 $2050.57 Saver 2 $3075.85

Month 11: Saver 1 $2055.69 Saver 2 $3083.54

Month 12: Saver 1 $2060.83 Saver 2 $3091.25

After setting interest rate to .04

Balances: Saver 1 $2067.70 Saver 2 $3101.55

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 72: Object Oriented Programming C++

Classes a Deeper Look (3)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

Class Definition

class SavingsAccount {

public:

SavingsAccount(double b)

{

savingsBalance = b >= 0 ? b : 0;

}

void calculateMonthlyInterest(void);

static void modifyInterestRate(double);

void printBalance(void) const;

private:

double savingsBalance;

static double annualInterestRate;

};

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 73: Object Oriented Programming C++

Classes a Deeper Look (4)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 9

Classes a Deeper Look (4)

friend Functions and friend Classes

Proxy Classes

friend Functions and friend Classes

Defined outside that class’s scope

Right to access the non-public (and public) members of the class

Friend function is often appropriate when a member function cannot be used

for certain operations

CODE

#include <iostream>

using namespace std;

// Count class definition

class Count

{

friend void setX(Count &, int); // friend declaration

public:

Count(int value) // constructor

{

x = value

} // end constructor Count

void print() const // output x

{

cout << x << endl;

} // end function print

private:

int x; // data member

}; // end class Count

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 74: Object Oriented Programming C++

Classes a Deeper Look (4)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

// function setX can modify private data of Count

// because setX is declared as a friend of Count

void setX(Count &c, int val)

{

c.x = val; // allowed because setX is a friend of Count

} // end function setX

int main()

{

Count counter(4); // create Count object

cout << "counter.x after instantiation: ";

counter.print();

setX(counter, 8); // set x using a friend function

cout << "counter.x after call to setX friend function: ";

counter.print();

return 0;

} // end main

OUTPUT

counter.x after instantiation: 4

counter.x after call to setX friend function: 8

Proxy Classes

Proxy class that allows you to hide even the private data of a class from

clients of the class

Providing clients of your class with a proxy class that knows only the public

interface to your class enables the clients to use your class’s services without

giving the clients access to your class’s implementation details.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 75: Object Oriented Programming C++

Classes a Deeper Look (4)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

CODE

// Implementation.h file

# include <iostream>

using namespace std;

class Implementation

{

public:

// constructor

Implementation(int v)

{

value = v;

} // end constructor Implementation

// set value to v

void setValue(int v)

{

value = v; // should validate v

} // end function setValue

// return value

int getValue() const

{

return value;

} // end function getValue

private:

int value; // data that we would like to hide from the client

}; // end class Implementation

// Interface.h file

# include "Implementation.h"

class Implementation; // forward class declaration required

class Interface

{

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 76: Object Oriented Programming C++

Classes a Deeper Look (4)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

public:

Interface(int); // constructor

void setValue1(int); // same public interface as

int getValue1() const; // class Implementation has

~Interface(); // destructor

private:

// requires previous forward declaration

Implementation *ptr;

}; // end class Interface

// constructor

Interface::Interface(int v)

{

ptr = new Implementation(v); // a new Implementation object

} // end Interface constructor

// call Implementation's setValue function

void Interface::setValue1(int v)

{

ptr->setValue(v);

} // end function setValue

// call Implementation's getValue function

int Interface::getValue1() const

{

return ptr->getValue();

} // end function getValue

// destructor

Interface::~Interface()

{

delete ptr;

} // end ~Interface destructor

// source.cpp file

#include "Interface.h" // Interface class definition

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 77: Object Oriented Programming C++

Classes a Deeper Look (4)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

int main()

{

Interface i(5); // create Interface object

cout << "Interface contains: " << i.getValue()

<< " before setValue" << endl;

i.setValue(10);

cout << "Interface contains: " << i.getValue()

<< " after setValue" << endl;

return 0;

} // end main

OUTPUT

Interface contains: 5 before setValue

Interface contains: 10 after setValue

Lab Task:

Q: Create two classes DMC (distance in meter and cm) and DFC (distance in

feet and inches). Write a program that can read values for the class objects

and can add one object of DMC with another object of DFC. Use a friend

function to carry out the addition operation. Return type for friend function

should be integer type value. Use set function to set values of objects and

display function to display values of objects. The display should be display the

result as shown as in output.

Your Output should appear as:

enter distance in m 5

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 78: Object Oriented Programming C++

Classes a Deeper Look (4)

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

enter distance in cm 120

enter distance in ft 48

enter distance in inches 24

5m-120cm+48 ft - 24 in = 10m-26cm = 33ft - 8in

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 79: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 10

File Processing

Sequential File

Random Access File

Some commands regarding File Processing

Creating a Random Access File

Accessing (Read / Display / Write / Search) a Random Access File

Sequential File

Each record needs to be placed in proper order.

Modifying a file may lead to data corruption.

For searching particular data we need to go through the entire file (Time

Consuming).

Modifying a file without data corruption is cumbersome and much

processing is required.

Sequential file occupies less space.

Random Access File

Each record in a file has specified equal number of bytes.

Record can be placed in any order.

Modification can be done without loss of data.

Searching for specific data is quick and easy.

Occupies more space. (Tradeoff between Space and Time).

Some commands regarding File Processing

Header file #include <fstream>

Writing into file ofstream outClientFile( "clients.txt", ios::out )

outClientFile << account << name << balance;

Reading from file ifstream inClientFile( "clients.txt", ios::in );

inClientFile >> account>>name>>balance

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 80: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

ostream member function seekp (“seek put”) object has a put pointer, which

indicates the byte number in the file at which the next output should be placed

istream member function seekg (“seek get”) object has a get pointer, which

indicates the byte number in the file from which the next input is to occur.

ios::in Open a file for input.

ios::out Open a file for output

ios::binary Open a file for binary ,i.e., non-text, input or output.

End-of-file Microsoft Windows <Ctrl-z>

Random Access File

ostream member function write outputs a fixed number of bytes, beginning at a

specific location in memory, to the specified stream.

istream member function read inputs a fixed number of bytes from the

specified stream to an area in memory beginning at a specified address.

Empty File Creation

ofstream outCredit( "credit.dat", ios::out | ios::binary );

outCredit.write( reinterpret_cast< constchar *>(&blankClient ),sizeof(ClientData

));

Read/Writing Data to File

fstream outCredit( "credit.dat", ios::in | ios::out | ios::binary );

// seek position in file of user-specified record

outCredit.seekp( (client.getAccountNumber() - 1 )* sizeof(ClientData ));

// write user-specified information in file

outCredit.write( reinterpret_cast< constchar *>(&client), sizeof(ClientData ));

Reading from file sequentially

ifstream inCredit( "credit.dat", ios::in | ios::binary );

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 81: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

inCredit.read( reinterpret_cast< char *>(&client ), sizeof(ClientData ));

Creating a Random Access File

ClientData.h

#ifndef CLIENTDATA_H #define CLIENTDATA_H #include <string> using namespace std; class ClientData { public: // default ClientData constructor ClientData(int = 0, string = "", string = "", double = 0.0); // accessor functions for accountNumber void setAccountNumber(int); int getAccountNumber() const; // accessor functions for lastName void setLastName(string); string getLastName() const; // accessor functions for firstName void setFirstName(string); string getFirstName() const; // accessor functions for balance void setBalance(double); double getBalance() const; private: int accountNumber; char lastName[15]; char firstName[10]; double balance; }; // end class ClientData #endif

ClientData.cpp #include <string> using namespace std; #include "ClientData.h" // default ClientData constructor ClientData::ClientData(int accountNumberValue,string lastNameValue, string firstNameValue, double balanceValue) {

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 82: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

setAccountNumber(accountNumberValue); setLastName(lastNameValue); setFirstName(firstNameValue); setBalance(balanceValue); } // end ClientData constructor // get account-number value int ClientData::getAccountNumber() const { return accountNumber; } // end function getAccountNumber // set account-number value void ClientData::setAccountNumber(int accountNumberValue) { accountNumber = accountNumberValue; // should validate } // end function setAccountNumber // get last-name value string ClientData::getLastName() const { return lastName; } // end function getLastName // set last-name value void ClientData::setLastName(string lastNameString) { // copy at most 15 characters from string to lastName const char *lastNameValue = lastNameString.data(); int length = lastNameString.size(); length = (length < 15 ? length : 14); strncpy_s(lastName, lastNameValue, length); lastName[length] = '\0'; // append null character to lastName } // end function setLastName // get first-name value string ClientData::getFirstName() const { return firstName; } // end function getFirstName // set first-name value void ClientData::setFirstName(string firstNameString) { // copy at most 10 characters from string to firstName const char *firstNameValue = firstNameString.data(); int length = firstNameString.size(); length = (length < 10 ? length : 9); strncpy_s(firstName, firstNameValue, length); firstName[length] = '\0'; // append null character to firstName } // end function setFirstName // get balance value double ClientData::getBalance() const { return balance; } // end function getBalance

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 83: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

// set balance value void ClientData::setBalance(double balanceValue) { balance = balanceValue; }

Source.cpp #include <iostream> #include <fstream> using namespace std; #include <cstdlib> #include "ClientData.h" // ClientData class definition int main() { ofstream outCredit("credit.txt", ios::out | ios::binary); // exit program if ofstream could not open file if (!outCredit) { cerr << "File could not be opened." << endl; exit(1); } // end if ClientData blankClient; // constructor zeros out each data member // output 100 blank records to file for (int i = 0; i < 100; i++) outCredit.write(reinterpret_cast< const char * >(&blankClient), sizeof(ClientData)); return 0; } // end main

Accessing (Read / Display / Write / Search) a Random Access File

Source.cpp

#include <iostream> #include <fstream> using namespace std; #include <iomanip> #include <cstdlib> #include "ClientData.h" // ClientData class definition int enterChoice(); void createTextFile(fstream&); void updateRecord(fstream&); void newRecord(fstream&); void deleteRecord(fstream&); void outputLine(ostream&, const ClientData &);

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 84: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

int getAccount(const char * const); enum Choices { PRINT = 1, UPDATE, NEW, DELETE, END }; int main() { fstream inOutCredit("credit.txt", ios::in | ios::out | ios::binary); // open file for reading and writing if (!inOutCredit) { cerr << "File could not be opened." << endl; exit(1); } int choice; // store user choice // enable user to specify action while ((choice = enterChoice()) != END) { switch (choice) { case PRINT: // create text file from record file createTextFile(inOutCredit); break; case UPDATE: // update record updateRecord(inOutCredit); break; case NEW: // create record newRecord(inOutCredit); break; case DELETE: // delete existing record deleteRecord(inOutCredit); break; default: // display error if user does not select valid choice cerr << "Incorrect choice" << endl; break; } // end switch inOutCredit.clear(); // reset end-of-file indicator } // end while return 0; } // enable user to input menu choice int enterChoice() { // display available options cout << "\nEnter your choice" << endl << "1 - store and print a formatted text file of accounts called ( print.txt ) for printing " << endl << "2 - update an account" << endl << "3 - add a new account" << endl << "4 - delete an account" << endl << "5 - end program\n? "; int menuChoice;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 85: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

cin >> menuChoice; // input menu selection from user return menuChoice; } // end function enterChoice // create formatted text file for printing void createTextFile(fstream &readFromFile) { // create text file ofstream outPrintFile("print.txt", ios::out); // exit program if ofstream cannot create file if (!outPrintFile) { cerr << "File could not be created." << endl; exit(1); } // end if outPrintFile << left << setw(10) << "Account" << setw(16) << "Last Name" << setw(11) << "First Name" << right << setw(10) << "Balance" << endl; // set file-position pointer to beginning of readFromFile readFromFile.seekg(0); // read first record from record file ClientData client; readFromFile.read(reinterpret_cast< char * >(&client),sizeof(ClientData)); // copy all records from record file into text file while (!readFromFile.eof()) { // write single record to text file if (client.getAccountNumber() != 0) // skip empty records outputLine(outPrintFile, client); // read next record from record file readFromFile.read(reinterpret_cast< char * >(&client), sizeof(ClientData)); } // end while } // end function createTextFile // update balance in record void updateRecord(fstream &updateFile) { // obtain number of account to update int accountNumber = getAccount("Enter account to update"); // move file-position pointer to correct record in file updateFile.seekg((accountNumber - 1) * sizeof(ClientData)); // read first record from file ClientData client; updateFile.read(reinterpret_cast< char * >(&client), sizeof(ClientData)); // update record if (client.getAccountNumber() != 0) {

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 86: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

outputLine(cout, client); // display the record // request user to specify transaction cout << "\nEnter charge (+) or payment (-): "; double transaction; // charge or payment cin >> transaction; // update record balance double oldBalance = client.getBalance(); client.setBalance(oldBalance + transaction); outputLine(cout, client); // display the record // move file-position pointer to correct record in file updateFile.seekp((accountNumber - 1) * sizeof(ClientData)); // write updated record over old record in file updateFile.write(reinterpret_cast< const char * >(&client), sizeof(ClientData)); } // end if else // display error if account does not exist cerr << "Account #" << accountNumber << " has no information." << endl; } // end function updateRecord // create and insert record void newRecord(fstream &insertInFile) { // obtain number of account to create int accountNumber = getAccount("Enter new account number"); // move file-position pointer to correct record in file insertInFile.seekg((accountNumber - 1) * sizeof(ClientData)); // read record from file ClientData client; insertInFile.read(reinterpret_cast< char * >(&client), sizeof(ClientData)); // create record, if record does not previously exist if (client.getAccountNumber() == 0) { char lastName[15]; char firstName[10]; double balance; // user enters last name, first name and balance cout << "Enter lastname, firstname, balance\n? "; cin >> setw(15) >> lastName; cin >> setw(10) >> firstName; cin >> balance; // use values to populate account values client.setLastName(lastName); client.setFirstName(firstName); client.setBalance(balance); client.setAccountNumber(accountNumber); // move file-position pointer to correct record in file

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 87: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 9

insertInFile.seekp((accountNumber - 1) * sizeof(ClientData)); // insert record in file insertInFile.write(reinterpret_cast< const char * >(&client), sizeof(ClientData)); } // end if else // display error if account already exists cerr << "Account #" << accountNumber << " already contains information." << endl; } // end function newRecord // delete an existing record void deleteRecord(fstream &deleteFromFile) { // obtain number of account to delete int accountNumber = getAccount("Enter account to delete"); // move file-position pointer to correct record in file deleteFromFile.seekg((accountNumber - 1) * sizeof(ClientData)); // read record from file ClientData client; deleteFromFile.read(reinterpret_cast< char * >(&client), sizeof(ClientData)); // delete record, if record exists in file if (client.getAccountNumber() != 0) { ClientData blankClient; // create blank record // move file-position pointer to correct record in file deleteFromFile.seekp((accountNumber - 1) * sizeof(ClientData)); // replace existing record with blank record deleteFromFile.write( reinterpret_cast< const char * >(&blankClient), sizeof(ClientData)); cout << "Account #" << accountNumber << " deleted.\n"; } // end if else // display error if record does not exist cerr << "Account #" << accountNumber << " is empty.\n"; } // end deleteRecord // display single record void outputLine(ostream &output, const ClientData &record) { output << left << setw(10) << record.getAccountNumber() << setw(16) << record.getLastName() << setw(11) << record.getFirstName() << setw(10) << setprecision(2) << right << fixed << showpoint << record.getBalance() << endl; } // end function outputLine // obtain account-number value from user int getAccount(const char * const prompt) {

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 88: Object Oriented Programming C++

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 10

int accountNumber; // obtain account-number value do { cout << prompt << " (1 - 100): "; cin >> accountNumber; } while (accountNumber < 1 || accountNumber > 100); return accountNumber; } // end function getAccount

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 89: Object Oriented Programming C++

Operator Overloading

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 11

Operator Overloading

Why Operation Overloading?

Syntax for Operator Functions

Some Restrictions on Overloading an Operator

Pointer this

Operator Functions as Member Functions and Non-member Functions

Overloading Binary Operators

Overloading the Stream Insertion (<<) Operator

Unary Operators (++ and --)

Overloading the pre-increment (++) operator

Why Operation Overloading?

Only built-in operations on classes are the assignment operator and the

member selection operator

Other operators cannot be directly applied to class objects +,*, == etc.

Syntax for Operator Functions

returnType operator operatorSymbol (formal parameter list)

Some Restrictions on Overloading an Operator

Cannot change the precedence of an operator

Associativity cannot be changed

Cannot change the number of parameters an operator takes

Cannot create new operators

The operators that cannot be overloaded are: . .* :: ?: sizeof

Pointer this

Sometimes, it is necessary for a member function to refer to the object as a

whole, rather than the object’s individual member variables

Every object of a class maintains a (hidden) pointer to itself, and the name of

this pointer is this

When an object invokes a member function, the member function references

the pointer this of the object

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 90: Object Oriented Programming C++

Operator Overloading

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

Operator Functions as Member Functions and Non-member Functions

Most operator functions can be either member functions or non-member

(friend) functions of a class

The function that overloads any of the operators (), [], ->,or = for a class

must be declared as a member of the class

C++ consists of both binary and unary operators

The return type of the functions that overload relational operators is bool

Overloading Binary Operators

Binary operators are (arithmetic, such as +; or relational, such as ==)

These operators can be overloaded as either a member function of the class

or as a friend function

General syntax to overload the binary (arithmetic or relational) Operators as

member functions

Function Prototype

returnType operator# (const className&) const;

Function Definition:

returnType className::operator#(const className& otherObject) const

{

//algorithm to perform the operation

return value;

}

General syntax to overload the binary (arithmetic or relational) Operators as Non-

member functions

Function Prototype

friend returnType operator#(const className&,const className&);

Function Definition:

returnType operator#(const className& firstObject, const className&

secondObject)

{

//algorithm to perform the operation

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 91: Object Oriented Programming C++

Operator Overloading

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

return value;

}

Overloading the Stream Insertion (<<) Operator

The operator function that overloads the insertion operator, <<, or the

extraction operator, >>, for a class must be a nonmember function of that

class

Function Prototype

friend ostream& operator<<(ostream&,const className&);

Function Definition:

ostream& operator<< (ostream& osObject,const className& cObject)

{

//local declaration, if any

//Output the members of cObject.

//osObject << . . .

//return the stream object.

return osObject;

}

Unary Operators (++ and --)

If the operator function is a member of the class, it has no parameters.

If the operator function is a nonmember—that is, a friend function of the

class—it has one parameter.

Overloading the Pre-Increment (++) Operator

General Syntax to Overload the Pre-Increment Operator++As A Member

Function

Function Prototype

className operator++();

Function Definition:

className className::operator++()

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 92: Object Oriented Programming C++

Operator Overloading

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

{

//increment the value of the object by 1

return*this;

}

General Syntax to Overload the Pre-Increment Operator++As A Nonmember

Function

Function Prototype

friend className operator++(className&);

Function Definition:

className operator++(className& incObj)

{

//increment incObj by 1

return incObj;

}

CODE:

newclock.h

#include<iostream>

using namespace std;

class clockType

{

friend ostream& operator<<(ostream&, const clockType&);

friend istream& operator>>(istream&, clockType&);

public:

void setTime(int hours, int minutes, int seconds);

//Function to set the member variables hr, min, and sec.

void getTime(int& hours, int& minutes, int& seconds)const;

//Function to return the time.

clockType operator++();

//Overload the pre-increment operator.

//Postcondition: The time is incremented by one second

bool operator==(const clockType& otherClock) const;

//Overload the equality operator.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 93: Object Oriented Programming C++

Operator Overloading

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

//Postcondition: Returns true if the time of this clock is equal to the time of otherClock

bool operator!=(const clockType& otherClock)const;

//Overload the not equal operator.

//Postcondition: Returns true if the time of this clock is not equal to the time of

otherClock

bool operator<(const clockType& otherClock)const;

//Overload the less than operator.

//Postcondition: Returns true if the time of this clock is less than the time of otherClock

bool operator>(const clockType& otherClock)const;

//Overload the greater than operator.

//Postcondition: Returns true if the time of this clock is greater than the time of

otherClock

clockType(int hours = 0, int minutes = 0, int seconds = 0);

//Constructor to initialize the object with the values

private:

int hr;

int min;

int sec;

};

newclock.cpp

#include"newClock.h"

using namespace std;

#include<iostream>

//Overload the pre-increment operator.

clockType clockType::operator++()

{

sec++;

if (sec>59)

{

sec = 0;

min++;

if (min>59)

{

min = 0;

hr++;

if (hr>23)

hr = 0;

}

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 94: Object Oriented Programming C++

Operator Overloading

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

}

return *this;

}

//Overload the equality operator.

bool clockType::operator==(const clockType& otherClock)const

{

return(hr == otherClock.hr && min == otherClock.min && sec == otherClock.sec);

}

//Overload the not equal operator.

bool clockType::operator!=(const clockType& otherClock)const

{

return(hr != otherClock.hr || min != otherClock.min || sec != otherClock.sec);

}

//Overload the less than operator.

bool clockType::operator<(const clockType& otherClock)const

{

return((hr<otherClock.hr) || (hr == otherClock.hr && min<otherClock.min) || (hr ==

otherClock.hr && min == otherClock.min && sec<otherClock.sec));

}

//Overload the greater than operator.

bool clockType::operator>(const clockType& otherClock)const

{

return((hr>otherClock.hr) || (hr == otherClock.hr && min>otherClock.min) || (hr ==

otherClock.hr && min == otherClock.min && sec>otherClock.sec));

}

void clockType::setTime(int hours, int minutes, int seconds)

{

if (0 <= hours && hours<24)

hr = hours;

else

hr = 0;

if (0 <= minutes && minutes<60)

min = minutes;

else

min = 0;

if (0 <= seconds && seconds<60)

sec = seconds;

else

sec = 0;

}

void clockType::getTime(int& hours, int& minutes, int& seconds)const

{

hours = hr;

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 95: Object Oriented Programming C++

Operator Overloading

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

minutes = min;

seconds = sec;

}

//Constructor

clockType::clockType(int hours, int minutes, int seconds)

{

setTime(hours, minutes, seconds);

}

//Overload the stream insertion operator.

ostream& operator<<(ostream& osObject, const clockType& timeOut)

{

if (timeOut.hr<10)

osObject << '0';

osObject << timeOut.hr << ':';

if (timeOut.min<10)

osObject << '0';

osObject << timeOut.min << ':';

if (timeOut.sec<10)

osObject << '0';

osObject << timeOut.sec;

return osObject; //return the ostream object

}

//overload the stream extraction operator

istream& operator>> (istream& is, clockType& timeIn)

{

char ch;

is >> timeIn.hr; //Step a

if (timeIn.hr <0 || timeIn.hr >= 24) //Step a

timeIn.hr = 0;

is.get(ch); //Read and discard :. Step b

is >> timeIn.min; //Step c

if (timeIn.min <0 || timeIn.min >= 60) //Step c

timeIn.min = 0;

is.get(ch); //Read and discard :. Step d

is >> timeIn.sec; //Step e

if (timeIn.sec <0 || timeIn.sec >= 60) //Step e

timeIn.sec = 0;

return is; //Step f

}

Source.cpp

#include<iostream>

#include"newClock.h"

using namespace std;

int main()

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 96: Object Oriented Programming C++

Operator Overloading

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

{

clockType myClock(5, 6, 23);

clockType yourClock;

cout << "myClock= " << myClock << endl;

cout << "yourClock= " << yourClock << endl;

cout << "Enter the time in the form in hr:min:sec ";

cin >> myClock;

cout << endl;

cout << "The new time of my Clock="<< myClock << endl;

++myClock;

cout << "After incrementing the time, myClock=" << myClock << endl;

yourClock.setTime(13, 35, 38);

cout << "After setting the time, yourClock=" << yourClock << endl;

if (myClock == yourClock)

cout << "The times of myClock and your Clock are equal." << endl;

else

cout << "The times of my Clock and your Clock are not equal." << endl;

if (myClock < yourClock)

cout << "The time of my Clock is less than or equal to the time of yourClock." <<

endl;

else

cout << "The time of myClock is greater than the time of yourClock." << endl;

return 0; }

OUTPUT:

myClock= 05:06:23

yourClock= 00:00:00

Enter the time in the form in hr:min:sec 16:8:7

The new time of my Clock=16:08:07

After incrementing the time, myClock=16:08:08

After setting the time, yourClock=13:35:38

The times of my Clock and your Clock are not equal.

The time of myClock is greater than the time of yourClock.

Lab Task: Implement the code given above with class clockType. Overload the

operators ++, ==,>, <, != as non-member friend functions. Verify that your output

is same as with member functions given in code above.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 97: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB 12

Inheritance

Inheritance

Types

Protected member

Accessing a base class member function through scope resolution operator

Inheritance

When creating a class, instead of writing completely new data members and

member functions, you can specify that the new class should inherit the

members of an existing class. This existing class is called the base class, and

the new class is called the derived class.

C++offers public, protected and private inheritance.

With public inheritance, every object of a derived class is also an object of

that derived class’s base class. However, base class objects are not objects of

their derived classes.

Shape class Derived classes Circle, Triangle, Rectangle

Types

With single inheritance, a class is derived from one base class. With multiple

inheritances, a derived class inherits from two or more (possibly unrelated)

base classes

Protected member

A base class’s protected members can be accessed within the body of that

base class, by members and friends of that base class, and by members and

friends of any classes derived from that base class

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 98: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

Declaring base-class data members as protected, derived classes can modify

the data directly.

Accessing a base class member function through scope resolution operator

When a derived-class member function redefines a base-class member

function, the base-class member can still be accessed from the derived class

by preceding the base-class member name with the base-class name and the

scope resolution operator (::).

CODE: Private Specifier

#include <iostream>

using namespace std;

// Base class

class Shape

{

public:

void setWidth(int w)

{

width = w;

}

void setHeight(int h)

{

height = h;

}

int getArea()

{

return (width * height);

}

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 99: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

private:

int width;

int height;

};

// Derived class

class Rectangle : public Shape

{

public:

int length;

void setLength(int l)

{

length = l;

}

int getvolume()

{

return length*getArea();

//return length*width*height is error because specifier in base class in

private (not protected)

}

};

int main(void)

{

Rectangle Rect;

Rect.setWidth(5);

Rect.setHeight(7);

Rect.setLength(11);

// Print the area of the object.

cout << "Total area: " << Rect.getArea() << endl;

cout << "Total volume: " << Rect.getvolume() << endl;

return 0;

OUTPUT:

Total area: 35

Total volume: 385

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 100: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

CODE: Protected Specifier

#include <iostream>

using namespace std;

// Base class

class Shape

{

public:

void setWidth(int w)

{

width = w;

}

void setHeight(int h)

{

height = h;

}

int getArea()

{

return (width * height);

}

protected:

int width;

int height;

};

// Derived class

class Rectangle : public Shape

{

public:

int length;

void setLength(int l)

{

length = l;

}

int getvolume()

{

return length*width*height;

// specifier in base class is protected so derived class can access width

and height

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 101: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 5

}

};

int main(void)

{

Rectangle Rect;

Rect.setWidth(5);

Rect.setHeight(7);

Rect.setLength(11);

// Print the area of the object.

cout << "Total area: " << Rect.getArea() << endl;

cout << "Total volume: " << Rect.getvolume() << endl;

return 0;

}

OUTPUT:

Total area: 35

Total volume: 385

CODE: Scope Resolution Operator

#include <iostream>

using namespace std;

// Base class

class Shape

{

public:

void setWidth(int w)

{

width = w;

}

void setHeight(int h)

{

height = h;

}

int getArea()

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 102: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 6

{

return (width * height);

}

void print()

{

cout << "width " << width<<endl;

cout << "heigth " << height<<endl;

}

private:

int width;

int height;

};

// Derived class

class Rectangle : public Shape

{

public:

int length;

void setLength(int l)

{

length = l;

}

int getvolume()

{

return length*getArea();

}

void print()

{

Shape::print();

cout << "length " << length<<endl;

}

};

int main(void)

{

Rectangle Rect;

Rect.setWidth(5);

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 103: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 7

Rect.setHeight(7);

Rect.setLength(11);

Rect.print();

// Print the area of the object.

cout << "Total area: " << Rect.getArea() << endl;

cout << "Total volume: " << Rect.getvolume() << endl;

return 0;

}

OUTPUT:

width 5

heigth 7

length 11

Total area: 35

Total volume: 385

CODE: Multiple Level Inheritance

#include <iostream>

using namespace std;

// Base class Shape

class Shape

{

public:

void setWidth(int w)

{

width = w;

}

void setHeight(int h)

{

height = h;

}

protected:

int width;

int height;

};

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 104: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 8

// Base class PaintCost

class PaintCost

{

public:

int getCost(int area)

{

return area * 70;

}

};

// Derived class

class Rectangle : public Shape, public PaintCost

{

public:

int getArea()

{

return (width * height);

}

};

int main(void)

{

Rectangle Rect;

int area;

Rect.setWidth(5);

Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.

cout << "Total area: " << Rect.getArea() << endl;

// Print the total cost of painting

cout << "Total paint cost: $" << Rect.getCost(area) << endl;

return 0;

}

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 105: Object Oriented Programming C++

Inheritance

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 9

OUTPUT:

Total area: 35

Total paint cost: $2450

Lab Task:

Create a database of a hospital for admitted patients. The information should

include

1) Name of patient

2) Date of admission

3) Disease

4) Date of Discharge

Create a base class Basic to store the above information. The member functions

get and print should input and print the record accordingly. Create a derived class

Detailed to store the age of patients. The derived class should have a member

function pediatric (patients less than twelve years in age), get to input data and a

member function print to display the records of all patients. Write a program to

test your output.

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 106: Object Oriented Programming C++

ReView Lab

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB

ReView Lab

Q1: Imagine a sensor at a bank door. Sensor senses people passing by the bank

door. People passing by door need to be counted until a threshold value is reached

and then the bank door is locked for some time.

Model this sensor with a class called sensor. The data item is int people and bool

door. A constructor initializes both to 0. A member function called Count ()

increments the people coming into by bank. Another function called decrement (),

decrements people in order to show people leaving the bank.

check () function includes a condition that if people in the bank are less than or

equal to 5 then bank door is open and door =0 but if the count is greater than or

equal to 10 the door should be closed be closed and door =1. The door will reopen

when the people in the bank are equal to 5 by people leaving the bank. Upon door

opening and closing the program should display “Door Opened” and “Door

Closed”. Each time the function Count and decrement are called the function

check in called in them to check status.

Include a program to test this class. This program should allow the user to push

one key (c) to move control to Count () function, and another key (d) to move

control to decrement () function. Pushing the (x) key should cause the program to

exit.

Your Output should appear as:

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

Door Closed

Fawad

Kha

n

For D

emon

stra

tion

Purpo

ses

Onl

y

Page 107: Object Oriented Programming C++

ReView Lab

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

Door Open

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

Door Closed

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

Door Open

enter a key c for entering bank ,d for leaving bank AND x for exit x

Q2: Write a program that converts a number entered in Roman numerals to

decimal. Your program should consist of a class, say, romanType. An object of

type romanType should do the following:

a. Store the number as a Roman numeral.

b. Convert and store the number into decimal form.

c. Print the number as a Roman numeral or decimal number as requested by the

user.

The decimal values of the Roman numerals are:

M 1000

D 500

C 100

Fawad

Kha

n

For D

emon

stra

tion Pu

rpos

es

Only

Page 108: Object Oriented Programming C++

ReView Lab

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

L 50

X 10

V 5

I 1

Your Output should appear as:

Please enter the Roman Numeral to convert to decimal : MXCIV

Roman Number MXCIV equals 1094

Please enter the Roman Numeral to convert to decimal : CCCLIX

Roman Number CCCLIX equals 359

Please enter the Roman Numeral to convert to decimal : MDCLXVI

Roman Number MDCLXVI equals 1666

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 109: Object Oriented Programming C++

ReView Lab

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 1

LAB

ReView Lab

Q1: Create a class called 'EMPLOYEE' that has

EMPCODE and EMPNAME as data members

member function getdata( ) to input data

member function display( ) to output data

Write a main function to create EMP, an array of EMPLOYEE objects.

Accept and display the details of at least 5 employees.

Your Output should appear as:

Enter employee details:

employee 1

NAME :aaaaaa

CODE :343

employee 2

NAME :sssssss

CODE :333

employee 3

NAME :zzzzzz

CODE :23

employee 4

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 110: Object Oriented Programming C++

ReView Lab

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 2

NAME :vvvvvvv

CODE :45

employee 5

NAME :tttttt

CODE :3445

Employee details are as follows :

NAME CODE

------------------------------

aaaaaa 343

sssssss 333

zzzzzz 23

vvvvvvv 45

tttttt 3445

Q2: Imagine a sensor at a bank door. Sensor senses people passing by the bank

door. People passing by door need to be counted until a threshold value is reached

and then the bank door is locked for some time.

Model this sensor with a class called sensor. The data item is int people and bool

door. A constructor initializes both to 0. A member function called Count ()

increments the people coming into by bank. Another function called decrement (),

decrements people in order to show people leaving the bank.

check () function includes a condition that if people in the bank are less than or

equal to 5 then bank door is open and door =0 but if the count is greater than or

equal to 10 the door should be closed be closed and door =1. The door will reopen

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 111: Object Oriented Programming C++

ReView Lab

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 3

when the people in the bank are equal to 5 by people leaving the bank. Upon door

opening and closing the program should display “Door Opened” and “Door

Closed”. Each time the function Count and decrement are called the function

check in called in them to check status.

Include a program to test this class. This program should allow the user to push

one key (c) to move control to Count () function, and another key (d) to move

control to decrement () function. Pushing the (x) key should cause the program to

exit.

Your Output should appear as:

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

Door Closed

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

Door Open

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

enter a key c for entering bank ,d for leaving bank AND x for exit c

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 112: Object Oriented Programming C++

ReView Lab

Prepared By: Fawad Khan FAST-NUCES Peshawar Campus 4

enter a key c for entering bank ,d for leaving bank AND x for exit c

Door Closed

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

enter a key c for entering bank ,d for leaving bank AND x for exit d

Door Open

enter a key c for entering bank ,d for leaving bank AND x for exit x

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y

Page 113: Object Oriented Programming C++

Projects List for Programming for Engineers II Repeat Students

Note: Repeat here means that the students who have been registered only in the lab (not theory

course).

1 Product Inventory Project

2 Movie Store

3 Airline / Hotel Reservation System

4 Student Grade Book Application

5 Bank Account Manager

6 Library Catalog

7 Tic-Tac-Toe

8 Hangman

9 Crossword Puzzle

10 Frogger

11 Text Adventure game

12 University Student Database

13 Memory Puzzle

14 Simon

15 Nibbles

16 Bus Reservation System

17 Supermarket Billing System

18 Phonebook Management System

19 PACMAN

20 Automated Teller Machine

Faw

ad K

han

For Dem

onst

ration

Pur

pose

s

Onl

y