OOP Lab Manuall

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 145

Data structures and algorithms Lab manual for BSCS/MCS

Department of CS, LGU

LAB MANUAL

Object Oriented Programming


(ll Semester SE)

Department of Computer Science


Lahore Garrison University

1
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Object Oriented Programming (CSC-321) Instructor:


Lab 1 Max Marks: 10
Date: Time Allowed :90 min

Introduction to Functions

Objective(s):

A program is a collection of small tasks that may depend on other tasks. You can use
two approaches to write a program.

1. Write code for all tasks in single place, in the main() function sequentially.


2. Divide code for all tasks into separate functions. Use main() function to execute
all other tasks.

Think for a while how painful it would have been to write all our code in single file or
single function. Hence you would choose the second approach to write a program.

Sr.No Call Type & Description

1 Call by Value

This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.

2 Call by Pointer

This method copies the address of an argument into the formal


parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.

3 Call by Reference

This method copies the reference of an argument into the formal


parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the

2
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

parameter affect the argument.

Program :

#include <iostream>

using namespace std;

// function declaration

int max(int num1, int num2);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

int ret;

// calling a function to get max value.

ret = max(a, b);

cout << "Max value is : " << ret << endl;

return 0;
3
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

// function returning the max between two numbers

int max(int num1, int num2) {

// local variable declaration

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

When the above code is compiled and executed, it produces the following result −

I kept max() function along with main() function and compiled the source code. While
running final executable, it would produce the following result −

Max value is : 200

Task#2:

#include <iostream>

using namespace std;

4
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int sum(int a, int b = 20) {

int result;

result = a + b;

return (result);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

int result;

// calling a function to add the values.

result = sum(a, b);

cout << "Total value is :" << result << endl;

// calling a function again as follows.

result = sum(a);

cout << "Total value is :" << result << endl;

5
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

return 0;

When the above code is compiled and executed, it produces the following result −

Total value is :300

Total value is :120

Program :

#include <iostream>

/* Function declaration */

void printNaturalNumbers(int start, int end);

int main()

int s, e;

cout<<”Enter lower range to print natural numbers:” ;

cin>>s;

cout<<"Enter upper limit to print natural numbers: ";

cin>>e;

printNaturalNumbers(s, e);

6
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

return 0;

/* Function definition */

void printNaturalNumbers(int start, int end)

cout<<start<< end;

while(start <= end)

cout<<start;

start++;

Output -

Enter lower range to print natural numbers: 5

Enter upper limit to print natural numbers: 10

Natural numbers from 5 to 10 are:

5, 6, 7, 8, 9, 10,

Program: Write a C++ function that returns a random prime number


on each function call.

/**

* C++ program to print random prime numbers

7
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

*/

#include <iostream>

#include <stdlib.h> // Used for rand() function

/* Function declaration */

int randPrime();

int main()

int i;

printf("Random 5 prime numbers are: \n");

for(i=1; i<=5; i++)

cout<< randPrime();

return 0;

/* Function definition */

8
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int randPrime()

int i, n, isPrime;

isPrime = 0;

while(!isPrime)

n = rand(); // Generates a random number

/* Prime checking logic */

isPrime = 1;

for(i=2; i<=n/2; i++)

if(n%i==0)

isPrime = 0;

break;

if(isPrime ==1)

9
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

return n;

Output -

Random 5 prime numbers are:

41

491

14771

25667

28703

Program:Write a C++ program to input a number and check the input


is even or odd. Define a function that accepts the number and return a
value 0 or 1. Return 0 if argument is even, otherwise return 1.

/**

* C++ check even odd using function

*/

#include <iostream>

10
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

/* Function declaration */

int evenOdd(int num);

int main()

int num, isEven;

cout<<"Enter a number: ";

cin>>num);

/* Function call */

isEven = evenOdd(num);

if(isEven == 0)

cout<<"The given number is EVEN.";

else

cout<<"The given number is ODD.";

return 0;

/* Function definition */

11
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int evenOdd(int num)

/* Return 0 if num is even */

if(num % 2 == 0)

return 0;

else

return 1;

Output -

Enter a number: 5

The given number is ODD.

Program :Write a C++ program to find cube of any number using


function.

/**
* C program to find cube of any number using function
*/
#include <iostream>

/* Function declaration */
double cube(double num);

int main()
{
int num;
double c;

12
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

/* Input number to find cube from user */


cout<<”Enter any number: ";
cin>>num;

c = cube(num);

cout<<” "Cube of 2"<< num;

return 0;
}

/**
* Function to find cube of any number
*/
double cube(double num)
{
return (num * num * num);
}
Program

#include <iostream>

#include <cmath>

using namespace std;

int main()

float base, exponent, result;

cout << "Enter base and exponent respectively: ";

13
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cin >> base >> exponent;

result = pow(base, exponent);

cout << base << "^" << exponent << " = " << result;

return 0;

Output

Enter base and exponent respectively: 2.3

4.5

2.3^4.5 = 42.44

Object Oriented Programming (CSC-321) Instructor:

14
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Lab 2 Max Marks: 10


Date: Time Allowed :90 min

Pointer

Learning Objectives:
With the help of pointers we can learn that in C++ program how we access the memory
and manipulate the address.It will be very easy for us to perform C++ program and
other C++ tasks such as dynamic memory allocation cannot be performed without
them.As you know every variable is a memory location and every memory location has
its address defined which can be accessed using ampersand (&) operator which
denotes an address in memory.

Topic:
Introduction to Pointer in C++
https://youtu.be/ifSs1aDzi9M

Introduction to CPP Pointer | Subroutines | C++ Video Tutorial


https://youtu.be/4bgabzer4OE

A pointer is a variable whose value is the address of another variable. Like any
variable or constant, you must declare a pointer before you can work with it.For a
C++ program, the memory of a computer is like a succession of memory cells, each
one byte in size, and each with a unique address. These single-byte memory cells are
ordered in a way that allows data representations larger than one byte to occupy
memory cells that have consecutive addresses.

Address in C++:

To understand pointers, you should first know how data is stored on the computer.Each
variable you create in your program is assigned a location in the computer's memory.
The value the variable stores is actually stored in the location assigned.To know where

15
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

the data is stored, C++ has an & operator. The & (reference) operator gives you the
address occupied by a variable.If var is a variable then, &var gives the address of that
variable.

Example

In this case, consider the following code fragment:

1 myvar = 25;
2 foo = &myvar;
3 bar = myvar;

The values contained in each variable after the execution of this are shown in the
following diagram: 
The values contained in each variable after the execution of this are shown in the
following diagram: 

First, we have assigned the value 25 to myvar (a variable whose address in memory we


assumed to be 1776).The second statement assigns foo the address of myvar, which
we have assumed to be 1776Finally, the third statement, assigns the value contained
in myvar to bar. This is a standard assignment operation, as already done many times
in earlier chapters.The main difference between the second and third statements is the

16
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

appearance of the address-of operator (&).The variable that stores the address of


another variable (like foo in the previous example) is what in C++ is called a pointer.
Pointers are a very powerful feature of the language that has many uses in lower level
programming. A bit later, we will see how to declare and use pointers.

Dereference Operator:

A variable which stores the address of another variable is called a pointer. Pointers are
said to "point to" the variable whose address they store.

An interesting property of pointers is that they can be used to access the variable they
point to directly. This is done by preceding the pointer name with the dereference
operator (*). The operator itself can be read as "value pointed to by".

Therefore, following with the values of the previous example, the following statement: 

  baz = *foo;

This could be read as: "baz equal to value pointed to by foo", and the statement would
actually assign the value 25 to baz, since foo is 1776, and the value pointed to
by 1776 (following the example above) would be 25.

17
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Declaring Pointer:

Due to the ability of a pointer to directly refer to the value that it points to, a pointer has
different properties when it points to a char than when it points to an int or a float. Once
dereferenced, the type needs to be known. And for that, the declaration of a pointer
needs to include the data type the pointer is going to point to.

The declaration of pointers follows this syntax:

type * name; 

where type is the data type pointed to by the pointer. This type is not the type of the
pointer itself, but the type of the data the pointer points to. For example:

1 int * number;char * character;double * decimals;


2
3
Types of Pointer:

18
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Sr.No Concept & Description

1 Null Pointers

C++ supports null pointer, which is a constant with a value


of zero defined in several standard libraries.

2 Pointer Arithmetic

There are four arithmetic operators that can be used on


pointers: ++, --, +, -

3 Pointers vs Arrays

There is a close relationship between pointers and arrays.

4 Array of Pointers

You can define arrays to hold a number of pointers.

5 Pointer to Pointer

C++ allows you to have pointer on a pointer and so on.

6 Passing Pointers to Functions

Passing an argument by reference or by address both


enable the passed argument to be changed in the calling
function by the called function.

7 Return Pointer from Functions

C++ allows a function to return a pointer to local variable,


static variable and dynamically allocated memory as well.

Solved Examples:

19
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Program :

#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer;

mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}

When it Compile it give following output:

firstvalue is 10
secondvalue is 20

Program :

#include <iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;

20
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue


p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed to by p1 = 10
*p2 = *p1; // value pointed to by p2 = value pointed to by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed to by p1 = 20

cout << "firstvalue is " << firstvalue << '\n';


cout << "secondvalue is " << secondvalue << '\n';
return 0;
}

When this program compile:


firstvalue is 10
secondvalue is 20

Pointer And Array:


Pointers are the variables that hold address. Not only can pointers store address of a
single variable, it can also store address of cells of an array.
Program

#include <iostream>using namespace std;


int main ()
{
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;

21
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << ", ";
return 0;
}
When this program compile:
10, 20, 30, 40, 50,

Pointer And Const:

Program:

#include <iostream>using namespace std;


void increment_all (int* start, int* stop)
{
int * current = start;
while (current != stop) {
++(*current); // increment value pointed
++current; // increment pointer
}
}
void print_all (const int* start, const int* stop)
{
const int * current = start;
while (current != stop) {
cout << *current << '\n';
++current; // increment pointer

22
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

}
}
int main ()
{
int numbers[] = {10,20,30};
increment_all (numbers,numbers+3);
print_all (numbers,numbers+3);
return 0;
}
When it compile it give following output:

y, 1603
Program :

Pointer To Function:

#include <iostream>
using namespace std;
int addition (int a, int b)
{ return (a+b); }
int subtraction (int a, int b)
{ return (a-b); }
int operation (int x, int y, int (*functocall)(int,int))
{
int g;
g = (*functocall)(x,y);
return (g);
}
int main ()
{
int m,n;

23
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int (*minus)(int,int) = subtraction;

m = operation (7, 5, addition);


n = operation (20, m, minus);
cout <<n;
return 0;
}

When it compile it give following output:

Program

Void pointers:
#include <iostream>
using namespace std;
void increase (void* data, int psize)
{
if ( psize == sizeof(char) )
{ char* pchar; pchar=(char*)data; ++(*pchar); }
else if (psize == sizeof(int) )
{ int* pint; pint=(int*)data; ++(*pint); }
}
int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));

24
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

increase (&b,sizeof(b));
cout << a << ", " << b << '\n';
return 0;
}
Program:
Pointer as Structure:
#include <iostream>

using namespace std;

struct Distance

int feet;

float inch;

};

int main()

Distance *ptr, d;

ptr = &d;

cout << "Enter feet: ";

cin >> (*ptr).feet;

cout << "Enter inch: ";

25
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cin >> (*ptr).inch;

cout << "Displaying information." << endl;

cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";

return 0;

What is the output of this program?

#include <iostream>

using namespace std;

int main()

int a = 5, b = 10, c = 15;

int *arr[ ] = {&a, &b, &c};

cout << arr[1];

return 0; }

What is the output of this program?

#include <iostream>

using namespace std;

int main()

char arr[20];

26
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int i;

for(i = 0; i < 10; i++)

*(arr + i) = 65 + i;

*(arr + i) = '\0';

cout << arr;

return(0);

What is the output of this program?

#include <iostream>

using namespace std;

int main()

char *ptr;

char Str[] = "abcdefg";

ptr = Str;

ptr += 5;

cout << ptr;

return 0;

27
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Object Oriented Programming (CSC-321) Instructor:


Lab 3 Max Marks: 10
Date: Time Allowed :90 min

Pointers
Program:
By using C++ pointer, write a C++ program to find the max of an
integral data set. The program will ask the user to input the number of
data values in the set and each value. Then your program will show
the max of the data set. See example below. Your C++ program will
use a function that accepts the array of data values and its size. The
return from the function is the pointer that points to the max value.

Enter number of data values: 3

Enter value 1: 21

28
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Enter value 2: 12

Enter value 3: 4

The max is 21.

Result: 2/9

Solution:

#include<iostream> #include<conio.h>
using namespace std;
int *findMax(int arr[],int n);
int main(){
int n,i,*p;
cout<<"Enter number of data values";
cin>>n;
int arr[n];
for(i=0;i<n;i++) {
cout<<"Enter value<<i+1<<":";
cin>>arr[i];
}
p=findMax(arr,n);
cout<<"The max value is:"<<*p;
getch();
return 0;
}

29
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int *findMax(int data[],int n){


int *max=data;
int i;
for(i=1;i<n;i++){
if(*max<*(max+i)) *max=*(max+i);
}
return max;
}

Program : Modify the solution of exercise 1 in order to print the


elements of the array in reverse order using a pointer.
Solution:

#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
int arr[5],i;
int *p=arr;
cout<<"Enter five numbers separated by space:";
cin>>*p>>*(p+1)>>*(p+2)>>*(p+3)>>*(p+4);
cout<<"Your numbers are:\n";
for(i=4;i>=0;i--)
cout<<*(p+i)<<endl;

30
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

getch();
return 0;

Program:. Write a C++ program to accept five integer values from


keyword.
The five values will be stored in an array using a pointer. Then print
the elements of the array on the screen.
Solution:

#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
int arr[5],i;
int *p=arr;
cout<<"Enter five numbers separated by space:";
cin>>*p>>*(p+1)>>*(p+2)>>*(p+3)>>*(p+4);
cout<<"Your numbers are:\n";
for(i=0;i<5;i++)
cout<<arr[i]<<endl;

getch();
return 0;

31
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Program :Write a C++ function to sort an array of ten integer values in


ascending order.
The function will accept two arguments-- a pointer that points to the
array and the array size. The function returns a pointer that points to
the sorted array.
Solution:

#include<iostream>
#include<conio.h>

using namespace std;


int *sortAsc(int *p, int size);
int main()
{
int arr[]={23,34,2,3,5,12,42,56,89,8};
int *p=sortAsc(arr,10);
//output the sorted array
int i;
for(i=0;i<10;i++)
cout<<*(p+i)<<endl;

getch();
return 0;

32
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int *sortAsc(int *p, int n){


int i,j;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(*(p+j)<*(p+i))
{
int temp=*(p+j);
*(p+j)=*(p+i);
*(p+i)=temp;
}
return p;
}

Program : Modify the solution of exercise 1 in order to sort the array


in descending order.
Solution:
#include<iostream>
#include<conio.h>

using namespace std;


int *sortAsc(int *p, int size);
int main()
{
int arr[]={23,34,2,3,5,12,42,56,89,8};
int *p=sortAsc(arr,10);
//output the sorted array
int i;

33
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

for(i=0;i<10;i++)
cout<<*(p+i)<<endl;

getch();
return 0;

int *sortAsc(int *p, int n){


int i,j;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(*(p+j)>*(p+i))
{
int temp=*(p+j);
*(p+j)=*(p+i);
*(p+i)=temp;
}
return p;
}

Program:Write a C++ program to accept five integer values from


keyword.
The five values will be stored in an array using a pointer. Then print
the elements of the array on the screen.
Solution:

34
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
int arr[5],i;
int *p=arr;
cout<<"Enter five numbers separated by space:";
cin>>*p>>*(p+1)>>*(p+2)>>*(p+3)>>*(p+4);
cout<<"Your numbers are:\n";
for(i=0;i<5;i++)
cout<<arr[i]<<endl;

getch();
return 0;

Program : Modify the solution of exercise 1 in order to print the


elements of the array in reverse order using a pointer .
Solution:

#include<iostream>
#include<conio.h>
using namespace std;

35
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int main()
{
int arr[5],i;
int *p=arr;
cout<<"Enter five numbers separated by space:";
cin>>*p>>*(p+1)>>*(p+2)>>*(p+3)>>*(p+4);
cout<<"Your numbers are:\n";
for(i=4;i>=0;i--)
cout<<*(p+i)<<endl;

getch();
return 0;

What did you learn :


I learn that,Pointers are necessary for dynamic memory location, many data structures,
and efficient handling of large amounts of data. Without pointers, you'd have to allocate
all the program data globally or in functions or the equivalent, and you'd have no
recourse if the amount of data grew beyond what you had originally allowed for. We
hesitate to use absolutes here, but as far as We know all modern computer languages
have pointers in some form or other.

36
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Object Oriented Programming (CSC-321) Instructor:


Lab 4 Max Marks: 10
Date: Time Allowed :90 min

Introduction to Structure
Objective(s):
A objective of data structure is to grouped a number of element together under one
name. These data elements, known as members, can have different types and different
lengths.

Tool(s) used:
Dev C++
Visual Studio

Properties of Structures :
1. By default, public
2. Doesn’t Support Inheritance

37
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

3. Object Created in Heap Memory


4. Call by value
5. Doesn’t Support Cleanup Process

Defining a Structure :
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member, for your program. The format of the struct
statement is this −

struct [structure tag] {


member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables
but it is optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

Accessing Structure Members:


To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name and

38
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

the structure member that we wish to access. You would use struct keyword to define
variables of structure type. Following is the example to explain usage of structure –
…………………………………………………………………………………………………….

Program :
#include <iostream>
#include <cstring>
using namespace std;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");

39
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Book2.book_id = 6495700;

// Print Book1 info


cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

// Print Book2 info


cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;
}……………………………………………………………………………………………
When the above code is compiled and executed, it produces the following result −
………………………………………………………………………………………………
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
………………………………………………………………………………………………

Structures as Function Arguments :


40
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

You can pass a structure as a function argument in very similar way as you pass any
other variable or pointer. You would access structure variables in the similar way as you
have accessed in the above example −
……………………………………………………………………………………………………

Program :
#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books book );

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification

41
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

strcpy( Book2.title, "Telecom Billing");


strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


printBook( Book1 );
// Print Book2 info
printBook( Book2 );

return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
……………………………………………………………………………………………………
When the above code is compiled and executed, it produces the following result −
……………………………………………………………………………………………………
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom

42
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Book id : 6495700
……………………………………………………………………………………………………

Object Oriented Programming (CSC-321) Instructor:


Lab 5 Max Marks: 10
Date: Time Allowed :90 min

Pointers to Structures:
You can define pointers to structures in very similar way as you define pointer to any
other variable as follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the & operator before the
structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use
the -> operator as follows −
struct_pointer->title;

43
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Let us re-write above example using structure pointer, hope this will be easy for you to
understand the concept −
……………………………………………………………………………………………………

Program
#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books *book );

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");

44
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

strcpy( Book2.subject, "Telecom");


Book2.book_id = 6495700;

// Print Book1 info, passing address of structure


printBook( &Book1 );

// Print Book1 info, passing address of structure


printBook( &Book2 );

return 0;
}

// This function accept pointer to structure as parameter.


void printBook( struct Books *book ) {
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}
……………………………………………………………………………………………………
When the above code is compiled and executed, it produces the following result −
……………………………………………………………………………………………………
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha

45
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Book subject : Telecom


Book id : 6495700
……………………………………………………………………………………………………
Program :

Nested Structure :
#include<iostream>
#include<cstring>
using namespace std;

struct address{
int house_no;
char city[50];
string country;
};
struct empl{

int emp_id;
char name[50];
string designation;
address address1;

};
int main(){

empl emp;
emp.emp_id=2;
emp.designation="Head";

46
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

emp.address1.house_no=5;
strcpy(emp.name,"Ali");
strcpy(emp.address1.city,"lahore");
emp.address1.country="paksitan";
//strcpy(emp.address1.country,"Pakistan");

cout<<emp.emp_id<<endl<<emp.designation<<endl<<emp.name<<endl<<emp.addres
s1.city<<endl<<emp.address1.house_no<<endl<<emp.address1.country<<endl;
return 0;
}

Object Oriented Programming (CSC-321) Instructor:


Lab 6 Max Marks: 10
Date: Time Allowed :90 min

Function Overloading
Objective(s):
Objectives of function is to specify more than one definition for a function name or an
operator in the same scope, which is called function overloading and operator
overloading respectively.

Tool(s) used:
Dev C++
Visual Studio

47
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

An overloaded declaration is a declaration that is declared with the same name as a


previously declared declaration in the same scope, except that both declarations have
different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use, by comparing the argument types you have used to call
the function or operator with the parameter types specified in the definitions. The
process of selecting the most appropriate overloaded function or operator is called
overload resolution.
Function Overloading in C++
You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the types and/or the number of
arguments in the argument list. You cannot overload function declarations that differ
only by return type.

Program :
#include <iostream>
using namespace std;

class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

int main(void) {

48
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

printData pd;

// Call print to print integer


pd.print(5);

// Call print to print float


pd.print(500.263);

// Call print to print character


pd.print("Hello C++");

return 0;
}

Program :
//function with same name and different parameters or arguments
#include<iostream>
using namespace std;

class book{
public:
void print(){

// id=a;
cout<<"Books Record "<<endl;

void print(int a){

49
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

// id=a;
cout<<"Book id is ="<<a<<endl;

}
void print(string t){

//title=t;

cout<<"Book Title is ="<<t<<endl;


}
void print(char c){

//code=c;
cout<<"Book title is ="<<c<<endl;

}
void print(int a,string s,char c){
//id=a;
// title=s;
//code=c;
cout<<"Book id is ="<<a<<endl;
cout<<"Book Title is ="<<s<<endl;
cout<<"Book title is ="<<c<<endl
}
};

50
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int main(){
book b;
b.print();
b.print(5);
b.print("Ali");
b.print('t');
b.print(5,"abc",'a');

return 0;

Object Oriented Programming (CSC-321) Instructor:


Lab 7 Max Marks: 10
Date: Time Allowed :90 min

Introduction To Classes
Objective(s):
A objective of classes is to specify the form of an object and it combines data
representation and methods for manipulating that data into one neat package. The data
and methods within a class are called members of the class.

Tool(s) used:
Dev C++
Visual Studio

51
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

How to define:
Class Name{
//Some data
//Some Function
};

Program :
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}

When it compile its output be:


Area:12.

52
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Program
#include <iostream>using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area () {return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main () {
Rectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
When it compile it output be:
rect area: 12
rectb area: 30

Program :

#include <iostream>
53
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

using namespace std;


class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2

54
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

volume = Box2.height * Box2.length * Box2.breadth;


cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When this program is compile:


Volume of Box1:210
Volume of Box:1560

Object Oriented Programming (CSC-321) Instructor:


Lab 8 Max Marks: 10
Date: Time Allowed :90 min

Constructor
Objective(s):
The objective of constructor is that it antialise the object automatically when it is
created.
Compiler identifies a given member function is a constructor by its name and the return
type.Constructor has the same name as that of the class and it does not have any
return type. Also, the constructor is always public.

55
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Tool(s) used:
Dev C++
Visual Studio

How to define:
class temporary
{
private:
int x;
float y;
public:
// Constructor
temporary(): x(5), y(5.5)
{
// Body of constructor
}
... .. ...
};

int main()
{
Temporary t1;
... .. ...
}

Program :
#include <iostream>
using namespace std;

56
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

class Rectangle {
int width, height;
public:
Rectangle (int,int);
int area () {return (width*height);}
};

Rectangle::Rectangle (int a, int b) {


width = a;
height = b;
}
int main () {
Rectangle rect (3,4);
Rectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

When this program compile it will give :


Rect area:12
Rectb area:25

Program :
#include <iostream>
using namespace std;

class Circle {
57
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

double radius;
public:
Circle(double r) { radius = r; }
double circum() {return 2*radius*3.14159265;}
};

int main () {
Circle foo (10.0); // functional form
Circle bar = 20.0; // assignment init.
Circle baz {30.0}; // uniform init.
Circle qux = {40.0}; // POD-like

cout << "foo's circumference: " << foo.circum() << '\n';


return 0;
}
When it compile it give:
Foos circumference:62.8319

The Class Constructor


A class constructor is a special member function of a class that is executed whenever
we create new objects of that class.
A constructor will have exact same name as the class and it does not have any return
type at all, not even void. Constructors can be very useful for setting initial values for
certain member variables.
Following example explains the concept of constructor −
Task 4:
#include <iostream>
using namespace std;
class Line {

58
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};

// Member functions definitions including constructor


Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}

// Main function for the program


int main() {
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;

59
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

When the above code is compiled and executed, it produces the


following result −
Object is being created
Length of line : 6

Object Oriented Programming (CSC-321) Instructor:


Lab 9 Max Marks: 10
Date: Time Allowed :90 min

Parameterized Constructor

A default constructor does not have any parameter, but if you need, a constructor can

have parameters. This helps you to assign initial value to an object at the time of its

creation as shown in the following example −

60
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Program :

#include <iostream>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(double len); // This is the constructor

private:

double length;

};

// Member functions definitions including constructor

Line::Line( double len) {

cout << "Object is being created, length = " << len << endl;

length = len;

61
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

void Line::setLength( double len ) {

length = len;

double Line::getLength( void ) {

return length;

// Main function for the program

int main() {

Line line(10.0);

// get initially set length.

cout << "Length of line : " << line.getLength() <<endl;

// set line length again

line.setLength(6.0);

cout << "Length of line : " << line.getLength() <<endl;

62
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

return 0;

When the above code is compiled and executed, it produces the

following result −

Object is being created, length = 10

Length of line : 10

Length of line : 6

Object Oriented Programming (CSC-321) Instructor:


Lab 10 Max Marks: 10
Date: Time Allowed :90 min

The Class Destructor

Objective(s):

63
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

A destructor is a special member function of a class that is executed whenever an

object of it's class goes out of scope or whenever the delete expression is applied to a

pointer to the object of that class.

A destructor will have exact same name as the class prefixed with a tilde (~) and it can

neither return a value nor can it take any parameters. Destructor can be very useful for

releasing resources before coming out of the program like closing files, releasing

memories etc.

Tool(s) used:

Dev C++

Visual Studio
Program :
Following example explains the concept of destructor −

#include <iostream>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(); // This is the constructor declaration

~Line(); // This is the destructor: declaration


64
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

private:

double length;

};

// Member functions definitions including constructor

Line::Line(void) {

cout << "Object is being created" << endl;

Line::~Line(void) {

cout << "Object is being deleted" << endl;

void Line::setLength( double len ) {

length = len;

double Line::getLength( void ) {

return length;

65
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

// Main function for the program

int main() {

Line line;

// set line length

line.setLength(6.0);

cout << "Length of line : " << line.getLength() <<endl;

return 0;

When the above code is compiled and executed, it produces the

following result −

Object is being created

Length of line : 6

Object is being deleted

Copy Constructor

66
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Program

#include<iostream>

#include<cstring>

using namespace std;

class test{

int code;

float price;

public:

test(int c,float p);

test(const test &t);

void disp();

};

test :: test(int c,float p){

code=c;

price=p;

67
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

test :: test(const test &t){

code=t.code;

price=t.price;

void test::disp(){

cout<<code<<endl<<price;

int main(){

test t1(5,6.6);

test t2(t1);

test t3=t2;

cout<<"object 1 value :"<<endl<<endl;

t1.disp();

cout<<"object 2 value :"<<endl<<endl;

t2.disp();

68
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cout<<"object 3 value :"<<endl<<endl;

t3.disp();

return 0;

Object Oriented Programming (CSC-321) Instructor:


Lab 11 Max Marks: 10
Date: Time Allowed :90 min

Constructor Overloading
Objective(s):
The objectives of constructor overloading is that we can use the constructor of same
name with different parameter.

Tools:
Dev C++
Visual Studio

69
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Program:
#include <iostream>
using namespace std;
class student{
int id ;
float marks;
public:
student(){
cout<<"heloo"<<endl;

}
student(int a){

id=a;

cout<<a<<endl;
}
student(int a, float b){

id=a;
marks =b;
cout<<"with two parameter "<<endl;

cout<<a<<" " <<b;

}
~student(){
cout<<"object is deleted"<<endl;

70
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

}
/*void display(){

cout<<id<<endl<<marks;

}*/
};

int main(){

student s,s1(5);
/*s1.display();
s2.display();
s.display();
return 0;
*/}

Program :
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration

private:
double length;

71
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

};

// Member functions definitions including constructor


Line::Line(void) {
cout << "Object is being created" << endl;
}
Line::~Line(void) {
cout << "Object is being deleted" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}

// Main function for the program


int main() {
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}

Program :
#include<iostream>

72
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

#include<cstring>

using namespace std;

class rectangle{

int length;
int height;
int width;
char name[10];

public:
rectangle()
{
length=10;
width=20;
height=30;
cout<<length<<endl<<height<<endl<<width<<endl<<endl;
}
rectangle(int len){
length=len;

cout<<"The length is:"<<len<<endl<<endl;

rectangle(int len,int wid){

73
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

length=len;
width=wid;
cout<<"The length and width is:"<<len<<" "<<wid<<endl<<endl;

}
rectangle(int len,int wid,int h){
length=len;

height=h;
h=30;
cout<<"mutiply"<<len*wid*h;
}
rectangle (char name){

name=name;
cin>>name;
cout<<name;
}
};
int main(){
//string a;
char a;
rectangle r,r1(5),r2(5,6),r3(1,2,3),r4(a);
}

74
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Object Oriented Programming (CSC-321) Instructor:


Lab 12,13 Max Marks: 10
Date: Time Allowed :90 min

Introduction to Inheritance

Objective(s):

One of the most important concepts in object-oriented programming is that of


inheritance. Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application. This also provides an opportunity
to reuse the code functionality and fast implementation time.

75
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

When creating a class, instead of writing completely new data members and member
functions, the programmer can designate 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 referred to as the derived class.

The idea of inheritance implements the is a relationship. For example, mammal IS-A
animal, dog IS-A mammal hence dog IS-A animal as well and so on.
Tool(s) used:

Dev C++

Visual Studio

Base and Derived Classes

A class can be derived from more than one classes, which means it can inherit data
and functions from multiple base classes. To define a derived class, we use a class
derivation list to specify the base class(es). A class derivation list names one or more
base classes and has the form −

class derived-class: access-specifier base-class

Where access-specifier is one of public, protected, or private, and base-class is the


name of a previously defined class. If the access-specifier is not used, then it is private
by default.

Consider a base class Shape and its derived class Rectangle as follows –

Program :

#include <iostream>

using namespace std;

// Base class

class Shape {

76
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

public:

void setWidth(int w) {

width = w;

void setHeight(int h) {

height = h;

protected:

int width;

int height;

};

// Derived class

class Rectangle: public Shape {

public:

int getArea() {

return (width * height);

};

77
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int main(void) {

Rectangle Rect;

Rect.setWidth(5);

Rect.setHeight(7);

// Print the area of the object.

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

return 0;

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

When the above code is compiled and executed, it produces the


following result –

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

Total area: 35

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

78
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Access Control and Inheritance

A derived class can access all the non-private members of its base class. Thus base-
class members that should not be accessible to the member functions of derived
classes should be declared private in the base class.

We can summarize the different access types according to - who can access them in
the following way −

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

Type of Inheritance

When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is specified
by the access-specifier as explained above.

We hardly use protected or private inheritance, but public inheritance is commonly


used. While using different type of inheritance, following rules are applied −

 Public Inheritance − When deriving a class from a public base


class, public members of the base class become public members of the
derived class and protected members of the base class
become protected members of the derived class. A base class's private
members are never accessible directly from a derived class, but can be
accessed through calls to the public and protected members of the base class.

 Protected Inheritance − When deriving from a protected base


class, public and protected members of the base class
become protected members of the derived class.

79
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

 Private Inheritance − When deriving from a private base


class, public and protected members of the base class become private
members of the derived class.

Multiple Inheritance

A C++ class can inherit members from more than one class and here is the extended
syntax −

class derived-class: access baseA, access baseB....

Where access is one of public, protected, or private and would be given for every


base class and they will be separated by comma as shown above. Let us try the
following example –

Program :

#include <iostream>

using namespace std;

// Base class Shape

class Shape {

public:

void setWidth(int w) {

width = w;

void setHeight(int h) {

80
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

height = h;

protected:

int width;

int height;

};

// Base class PaintCost

class PaintCost {

public:

int getCost(int area) {

return area * 70;

};

// Derived class

class Rectangle: public Shape, public PaintCost {

public:

int getArea() {

81
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

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;

82
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

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

When the above code is compiled and executed, it produces the


following result −

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

Total area: 35

Total paint cost: $2450

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

83
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Object Oriented Programming (CSC-321) Instructor:


Lab 14 Max Marks: 10
Date: Time Allowed :90 min

Multilevel Inheritance:
Objective(s):

“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more
than one base class. Theinheritance we learnt earlier had the concept of one base
class or parent. The problem with “multiple inheritance” is that the derived class will
have to manage the dependency on two base classes.

Program :

#include<iostream>

#include<cstring>

using namespace std;

//base class

class animal {

protected:

int legs;

string hair;

public:

void body(int a,string b){

84
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

legs=a;

hair=b;

};

//child class

class lion:public animal{

protected :

string color;

public:

void color1(string c){

color=c;

cout<<c<<endl;

void bodgshape(){

cout<< legs<<endl<<hair;

85
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

};

class lionspeed:public lion{

public:

void speed(){

cout<<"80 kmph";

};

int main(){

//lion l;

//l.body(4,"hair");

//l.color1("blue");

//l.bodgshape();

86
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

lionspeed s;

s.body(4,"Hair");

s.color1("white");

s.bodgshape();

s.speed();

Output:

white

Hair80 kmph

Object Oriented Programming (CSC-321) Instructor:


Lab 15,16 Max Marks: 10
Date: Time Allowed :90 min
Association

87
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Objective(s):
Association is a simple structural connection or channel between classes and is a
relationship where all objects have their own lifecycle and there is no owner.
Lets take an example of Department and Student.
Multiple students can associate with a single Department and single student can
associate with multiple Departments, but there is no ownership between the objects and
both have their own lifecycle. Both can create and delete independently.

Here is respective Model and Code for the above example.

Program :
#include<iostream.h>

class Student;

class Department
{
char* name_p;

public:

Department(char *dName)
{
cout<<"Department::ctor\n";
name_p = new char(sizeof(strlen(dName)));
name_p = dName;
}

char* dName() const


{

88
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

return(name_p);
}

~Department()
{
cout<<"Department::dtor\n";
delete(name_p);
}

};

class Student
{
char* name_p;

public:

Student(char *sName)
{
cout<<"Student::ctor\n";
name_p = new char(sizeof(strlen(sName)));
name_p = sName;
}

char* sName()const
{
return(name_p);
}

89
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

~Student()
{
cout<<"Student::dtor\n";
delete(name_p);
};
};

class Course
{
Student * std_p;
Department * dept_p;
char * courseName_p;

static unsigned int index;


static Course *courseList[4];

public:

Course(char* crseName, Student* student, Department* dept):


courseName_p(0), std_p(student), dept_p(dept)
{
cout<<"Course:ctor\n";

if (index < 4)
{
courseName_p = new char(sizeof(strlen(crseName)));

90
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

courseName_p = crseName;

//insert this Course in courseList


courseList[index] = this;
++index;
}
else
{
cout<<"Cannot accomodate any more Course\n";
}
};

~Course()
{
cout<<"Course:dtor\n";
delete (courseName_p);
};

static char* findStudent(char *crseName, char* deptName)


{
for(int i=0; i<index; i++)
{
if ( (courseList[i]->getCourseName() == crseName) &&
(courseList[i]->getDeptName() == deptName) )
{
return(courseList[i]->getStdName());
}
}

91
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

char * getStdName()const {return(std_p->sName());};


char * getDeptName() const {return(dept_p->dName());};
char * getCourseName()const {return(courseName_p);};
};

unsigned int Course::index =0;


Course* Course::courseList[4] = {0,0,0,0};

int main()
{
int i;

cout<<"\nExample of Association class...\n";


cout<<"-----------------------------------\n\n";

cout<<"We have got 4 students ...\n";


Student *studentNames[4] = {new Student("Meera"), new Student("Moina"), new
Student("Teena"), new Student("Mridula")} ;

cout<<"\n";

cout<<"We have got 2 Departments...\n";


Department *departNames[2] = {new Department("Mathemetics"), new
Department("ComputerSceince")} ;

92
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cout<<"\n";

cout<<"Here class Course Associates Student and Department, with a Course


name ...\n";
Course course1("DataStructure",studentNames[0], departNames[1]);
Course course2("Maths",studentNames[3], departNames[0]);
Course course3("Geometry",studentNames[2], departNames[0]);
Course course4("CA",studentNames[1], departNames[1]);

cout<<"\n";

cout<<"Finding a Student using Course and Department...\n";


cout<<"Student who has taken Maths Course in Mathemetics Department
is:"<<Course::findStudent("Maths", "Mathemetics")<<endl;

cout<<"\n";

cout<<"Deletion of objects...\n\n";

for(i=0; i<4; ++i)


{
delete studentNames[i];
}

cout<<"\n";

for(i=0; i<2; ++i)


{

93
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

delete departNames[i];
}

cout<<"\n";

return(0);
}

output:
------

Example of Association class...


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

We have got 4 students ...


Student::ctor
Student::ctor
Student::ctor
Student::ctor

We have got 2 Departments...


Department::ctor
Department::ctor

Here class Course Associates Student and Department, with a Course name ...
Course:ctor
Course:ctor
Course:ctor

94
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Course:ctor

Finding a Student using Course and Department...


Student who has taken Maths Course in Mathemetics Department is:Mridula

Deletion of objects...

Student::dtor
Student::dtor
Student::dtor
Student::dtor
Department::dtor
Department::dtor
Course:dtor
Course:dtor
Course:dtor
Course:dtor

Object Oriented Programming (CSC-321) Instructor:


Lab 17 Max Marks: 10
Date: Time Allowed :90 min

95
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Aggregation
Objective(s):
To qualify as an aggregation, a whole object and its parts must have the following
relationship:
• The part (member) is part of the object (class)
• The part (member) can belong to more than one object (class) at a time
• The part (member) does not have its existence managed by the object (class)
• The part (member) does not know about the existence of the object (class)
• pointer variables
• Use reference that point the object that lives outside teh scope
• Pointer object /deep copy
• Not responsible for creation/destruction
Like a composition, an aggregation is still a part-whole relationship, where the parts are
contained within the whole, and it is a unidirectional relationship. However, unlike a
composition, parts can belong to more than one object at a time, and the whole object is
not responsible for the existence and lifespan of the parts. When an aggregation is
created, the aggregation is not responsible for creating the parts. When an aggregation
is destroyed, the aggregation is not responsible for destroying the parts.

Program :
class alpha
{
int x;
public:
void read-x()
{
cin>>x;
}
void print.x()

96
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

{
cout<<x;
}
};
class beta
{
int y;
alpha *a;
public:
beta(alpha*p)
}
a=p;
}
void main()
{
alpha a1;
beta b1(&a1);
}
Task 2:
#include<iostream>
using namespace std;
class processor{
private:
double clockspeed;
public:

processor(){
clockspeed=2.6;

97
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

}
processor(double cspeed){
clockspeed=cspeed;
}

double getclockspeed(){

return clockspeed;
}
void setclockspeed(double cs){

clockspeed=cs;

}
};
class computer{

processor *processor1;

public:
void set processor (processor *processor1){

this->processor1= new processor();//deep copy

this->processor1->setclockspeed(processor1->getclockspeed());

98
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

this->processor1->setclockspeed(11111);

}
void print(){
//cout<<"Operating System"<<operatingsystem;
cout<<"Clock speed "<<processor1->getclockspeed();
}
};
int main(){
processor p(5.5);
//calling parameterize contructor
{

computer c1;
c1.setprocessor(&p);

)
c1.print();
}
cout<<" Clock Speed "<<p.getclockspeed();
return 0;
}

Object Oriented Programming (CSC-321) Instructor:


Lab 18 Max Marks: 10
Date: Time Allowed :90 min

99
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Composition
Composition is again specialize form of Aggregation. It is a strong type of Aggregation.
Here the Parent and Child objects have coincident lifetimes. Child object dose not have
it's own lifecycle and if parent object gets deleted, then all of it's child objects will also be
deleted.

Implementation details:

1. Typically we use normal member variables


2. Can use pointer values if the composition class automatically handles
allocation/deallocation
3. Responsible for creation/destruction of subclasses

Lets take an example of a relationship between House and it's Rooms.

House can contain multiple rooms there is no independent life for room and any room
can not belong to two different house. If we delete the house room will also be
automatically deleted.

Here is respective Model and Code for the above example.

Program :
#include<iostream.h>

class House;

class Room
{
public:

100
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Room()
{
};

static void createRoom_v(Room* (&room), House* hse, char* name)


{
room = new Room(hse, name);
}

Room(House* hse, char* myName)


{
cout<<"Room::ctor\n";
myHse_p = hse;

if(NULL != myHse_p)
{
name_p = new char(sizeof(strlen(myName)));
name_p = myName;
}
else
{
cout<<"Oops House itself is not Created Yet ...\n";
}
};

~Room()
{

101
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cout<<"Room:dtor\n";
myHse_p = NULL;
delete (name_p);
};

void disp()
{
cout<< name_p;
cout<<"\n";
}

static void initList_v(Room *(& roomsList_p)[3])


{
roomsList_p[3] = new Room[3];
}

private:
House * myHse_p;
char * name_p;
};

class House
{
public:

House(char *myName)
{
cout<<"House::ctor\n";

102
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

name_p = new char(sizeof(strlen(myName)));;


name_p = myName;

Room::initList_v(roomsList_p);

Room* myRoom;
Room::createRoom_v(myRoom, this, "Kitchen");
roomsList_p[0] = myRoom;

Room::createRoom_v(myRoom, this, "BedRoom");


roomsList_p[1] = myRoom;

Room::createRoom_v(myRoom, this, "Drwaing Room");


roomsList_p[2] = myRoom;
}

~House()
{
cout<<"House:dtor\n";
unsigned int i;

cout<<"Delete all the Rooms ...\n";


for(i=0; i<3; ++i)
{
if(roomsList_p[i] != NULL)
{
delete (roomsList_p[i]);
}

103
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

}
delete [] roomsList_p;
delete (name_p);
}

void disp()
{
cout<<"\n\nName of the House :"<<name_p;

if(roomsList_p != NULL)
{
unsigned int i;
cout<<"\n\nRooms details...\n";
for(i=0; i<3; ++i)
{
if(NULL != roomsList_p[i])
{
roomsList_p[i]->disp();
}
}
cout<<"\n\n";
}
}

private:
char* name_p;
Room* roomsList_p[3];

104
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

};

int main()
{

cout<<"\nExample of Composition Relationship\n";


cout<<"-----------------------------------------\n\n";
House hse("Vishranti Nilaya");

cout<<"\n\nHouse details...\n";
hse.disp();

cout<<"Here House itself creates the Rooms and Deletes as well, before it gets
deletd...\n";

return(0);
}

output:
-------
Example of Composition Relationship
-----------------------------------------

House::ctor
Room::ctor
Room::ctor
Room::ctor
House details...

105
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Name of the House :Vishranti Nilaya

Rooms details...
Kitchen
BedRoom
Drwaing Room

Here House itself creates the Rooms and Deletes as well, before it gets deletd...
House:dtor
Delete all the Rooms ...
Room:dtor
Room:dtor
Room:dtor

Program :
#include <iostream>
#include <string>
using namespace std;
class Birthday{
public:
Birthday(int cmonth, int cday, int cyear){
cmonth = month;
cday = day;
cyear = year;
}

106
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

void printDate(){
cout<<month <<"/" <<day <<"/" <<year <<endl;
}
private:
int month;
int day;
int year;

};

class People{

public:
People(string cname, Birthday cdateOfBirth):name(cname),
dateOfBirth(cdateOfBirth)
{

}
void printInfo(){
cout<<name <<" was born on: ";
dateOfBirth.printDate();
}

private:
string name;
Birthday dateOfBirth;

};

107
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int main() {

Birthday birthObject(7,9,97);
People infoObject("Lenny the Cowboy", birthObject);
infoObject.printInfo();

}-------------------------------------------------------------------------------------------------------------

Object Oriented Programming (CSC-321) Instructor:


Lab 19 Max Marks: 10
Date: Time Allowed :90 min

108
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Friend Function and Friend Classes


Objective(s):
A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class. Even though the prototypes for
friend functions appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends.
How to define:
To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows −
class Box {
double width;

public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place
a following declaration in the definition of class ClassOne −
friend class ClassTwo;

Program :
#include <iostream>
using namespace std;

109
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

class Box {
double width;

public:
friend void printWidth( Box box );
void setWidth( double wid );
};

// Member function definition


void Box::setWidth( double wid ) {
width = wid;
}

// Note: printWidth() is not a member function of any class.


void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}

// Main function for the program


int main() {
Box box;

// set box width without member function

110
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return 0;
}

When the above code is compiled and executed, it produces the


following result −
Width of box : 10

Program :
Addition of members of two different classes using friend Function
#include <iostream>
using namespace std;

// forward declaration
class B;
class A {
private:
int numA;
public:
A(): numA(12) { }
// friend function declaration
friend int add(A, B);
};
class B {
private:
int numB;

111
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

public:
B(): numB(1) { }
// friend function declaration
friend int add(A , B);
};
// Function add() is the friend function of classes A and B
// that accesses the member variables numA and numB
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}

Output
Sum: 13

Object Oriented Programming (CSC-321) Instructor:


Lab 20, 21 Max Marks: 10
Date: Time Allowed :90 min

112
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Operator Overloading (Operator and Function)


Objective(s):
The objectives of operator overloading is that it profoundly used by programmers to
make program intuitive.
Unary Operators Overloading in C++
The unary operators operate on a single operand and following are the examples of
Unary operators
• The increment (++) and decrement (--) operators.
• The unary minus (-) operator.
• The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this
operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime
they can be used as postfix as well like obj++ or obj--.

Program :
#include<iostream>
using namespace std;
class box{
int a,b,c;
public:
void getdata(int x,int y,int z);

void operator++();

void disp();
};

void box::getdata(int x,int y,int z){

113
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

a=x;
b=y;
c=z;
}
void box::operator++(){
a=++a;
b=++b;
c=++c;

void box::disp(){
cout<<"first : \t\t"<<a<<endl<<"second : \t\t"<<b<<endl<<"third : \t\t"<<c<<endl;
}
int main(){
box b1,b2;
b1.getdata(-2,3,4);
b1.disp();
++b1;
b1.disp();
}

Program :
#include <iostream>
using namespace std;

114
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}

115
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

};
int main() {
Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation


D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

return 0;
}

When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11

Binary Operators Overloading in C++


The binary operators take two arguments and following are the examples of Binary
operators. You use binary operators very frequently like addition (+) operator,
subtraction (-) operator and division (/) operator.

Program :
//binary operator overloading

#include<iostream>
using namespace std;
class student{
private:
int num;

116
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

int marks;
public:
student(){
num=0;
marks=0;

}
student(int n,int m){
num=n;
marks=m;

}
student operator +(student s){
//first num direct accessing the value but accessing second object
value we (s.num)by accessing second object value
student temp;//creating object for returning object becasue
we have student as a return type

temp.num=num+s.num;
temp.marks=marks+s.marks;
return temp;
}
void display(){
cout<<"number :"<<num<<endl<<"marks :"<<marks<<endl;
}
};
int main(){
117
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

student s(2,3),s1(6,7),s2;
//s=student(6,7);//explicitly
//s1=student(6,7);
s2=s+s1;
cout<<"value of 1"<<endl;
s.display();
cout<<"value of 2"<<endl;
s1.display();
cout<<"value of 3"<<endl;
s2.display();

return 0;
}

Program :
#include <iostream>
using namespace std;

class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

public:

double getVolume(void) {
return length * breadth * height;
}

118
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

void setLength( double len ) {


length = len;
}

void setBreadth( double bre ) {


breadth = bre;
}

void setHeight( double hei ) {


height = hei;
}

// Overload + operator to add two Box objects.


Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};

// Main function for the program


int main() {

119
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Box Box1; // Declare Box1 of type Box


Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();

120
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cout << "Volume of Box3 : " << volume <<endl;

return 0;
}

When the above code is compiled and executed, it produces the


following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Object Oriented Programming (CSC-321) Instructor:


Lab 22 Max Marks: 10

121
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Date: Time Allowed :90 min

Ostream,Istream Operator Overloading


Objective(s):
++ is able to input and output the built-in data types using the stream extraction
operator >> and the stream insertion operator <<. The stream insertion and
stream extraction operators also can be overloaded to perform input and output
for user-defined types like an object.
Here, it is important to make operator overloading function a friend of the class
because it would be called without creating an object.
Program :
#include<iostream>
using namespace std;
//in this program we r going to use cout and cin overloading.
//for this we use two classess
//ostream = which is used for output
//istream =for input
//combination of both is iostream whict is already mentioned in our header file.
// lets start
class Student{

int id;
string name;
public :

void set(int a,string b){

122
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cin>>a>>b;
id=a;
name=b;
}
void get(){

cout<<"set of id :"<<id<<endl;
cout<<"set of id :"<<name<<endl;

}
// now here we declare two class which are ostream and
istream,basically we can overload cout,cin by using friend class function
//now we are using two friend function of two classess
//mostly we only declares friend function in class and define outside
the class but here we declare and define friend function in the class

friend void operator >> (istream &input,Student &s1){

cout<<"Plaese Enter Values :"<<endl;


input >>s1.id>>s1.name;

friend void operator << (ostream &output,Student &s1){

output<<"id of student is :"<<s1.id<<endl<<endl<<"Name of student


is :"<<s1.name;

123
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

}
};
int main(){
int a;
string b;
Student s;
s.set(a,b);
s.get();
cout<<"Now we are going to display Operator Overloading"<<endl;
cin>>s;
cout<<s;

}
Program :
#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;

124
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

}
Distance(int f, int i) {
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output, const Distance &D ) {
output << "F : " << D.feet << " I : " << D.inches;
return output;
}

friend istream &operator>>( istream &input, Distance &D ) {


input >> D.feet >> D.inches;
return input;
}
};

int main() {
Distance D1(11, 10), D2(5, 11), D3;
cout << "Enter the value of object : " << endl;
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;

return 0;
}

125
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

When the above code is compiled and executed, it produces the


following result −
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10

Object Oriented Programming (CSC-321) Instructor:

126
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Lab 23 Max Marks: 10


Date: Time Allowed :90 min

Polymorphism
Objective(s):
Polymorphism is an object oriented programming concept that allows a class to have different
form or behavior for example a trumpet a flute .

Task 1:
include<iostream>
using namespace std;
class A
{
int a;
public:
A()
{
a=0;
}
A(int x)
{
a=x;
}
virtual void display()
//pure virtual function
/*C++ virtual function is a member function of a class, whose functionality can be over-
ridden

in its derived classes. The whole function body can be replaced with a new set of
implementation
in the derived class. The concept of c++ virtual functions is different from C++
Function overloading.

127
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

C++ Virtual Function - Properties:

C++ virtual function is,

* A member function of a class


* Declared with virtual keyword
* Usually has a different functionality in the derived class
* A function call is resolved at run-time*/
{
cout<<"The value of a is:"<<a<<endl;
}
};
class B:public A{
int b;
public:
B():A()
{
b=0;
}
B(int x,int y):A(x)
{
b=y;
}

void display(){
//A::display();
cout<<"The value of b is"<<b<<endl;
}

128
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

};
class C:public A{
int c;
public:
C():A()
{
c=0;

}
C(int x, int y):A(x)
{
c=y;
}
void display(){
A::display();

cout<<"The value of c is:"<<c<<endl;


}

};

int main()
{

B x(10,50);
x.display();
cout<<endl;
C y;
y.display();

129
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

A z;
z.display();
}

Program :
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a;
height=b; }
virtual int area ()
{ return 0; }
};
class Rectangle: public Polygon {

public:
int area ()
{ return width * height; }
};

class Triangle: public Polygon {


public:
int area ()
{ return (width * height / 2); }

130
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

};

int main () {
Rectangle rect;
Triangle trgl;
Polygon poly;
Polygon * ppoly1 ;//declare the pointer
ppoly1= &rect;// store the address
Polygon * ppoly2 ;
ppoly2= &trgl;
Polygon * ppoly3 ;
ppoly3 = &poly;
ppoly1->set_values (4,5);//call the value
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';

cout << ppoly3->area() << '\n';


return 0;
}

Task 3:
#include<iostream>
using namespace std;
class base{
public:
void disp()

131
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

{
cout<<"base class"<<endl;
}
virtual void show()
{
cout<<"Base class show:";
}
};
class derived:public base
{
void disp()
{
cout<<"derived class"<<endl;
}
void show()
{
cout<<"derived class show";
}
};
int main()
{
base*ptr;
base objb;
objb.disp();
objb.show();
derived objd;
ptr=&objd;//store address
ptr->disp();//call the function

132
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

ptr->show();
return 0;
}

Object Oriented Programming (CSC-321) Instructor:


Lab 24 Max Marks: 10
Date: Time Allowed :90 min

Virtual Function
A virtual function is a function in a base class that is declared using the
keyword virtual. Defining in a base class a virtual function, with another version in a
derived class, signals to the compiler that we don't want static linkage for this function.

What we do want is the selection of the function to be called at any given point in the
program to be based on the kind of object for which it is called. This sort of operation is
referred to as dynamic linkage, or late binding.

Pure Virtual Functions


It is possible that you want to include a virtual function in a base class so that it may be
redefined in a derived class to suit the objects of that class, but that there is no
meaningful definition you could give for the function in the base class.

Program :
// CPP program to illustrate

// concept of Virtual Functions

#include<iostream>

using namespace std;

class base

133
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

public:

virtual void print ()

{ cout<< "print base class" <<endl; }

void show ()

{ cout<< "show base class" <<endl; }

};

class derived:public base

public:

void print ()

{ cout<< "print derived class" <<endl; }

void show ()

{ cout<< "show derived class" <<endl; }

};

int main()

base *bptr;

derived d;

bptr = &d;

134
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

//virtual function, binded at runtime

bptr->print();

// Non-virtual function, binded at compile time

bptr->show();

Program 2 :
#include<iostream>

using namespace std;

class A{

public:

virtual void disp()=0;

};

class B:public A{

private:

int val1;

public:

B(int x){

val1= x;

void disp(){

135
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cout<<"value of Clas B "<<val1<<endl;

};

class C:public A{

private:

int val2;

public:

C(int x){

val2= x;

void disp(){

cout<<"value of Clas C "<<val2<<endl;

};

int main(){

A *basep;

B objb(100);

basep=&objb;

basep->disp();

C objc(200);

basep=&objc;

basep->disp();

return 0;

136
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

Object Oriented Programming (CSC-321) Instructor:


Lab 25,26 Max Marks: 10
Date: Time Allowed :90 min

Templates
Objective(s):
Templates are the foundation of generic programming, which involves writing code in a way
that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library
containers like iterators and algorithms are examples of generic programming and have been
developed using template concept.
There is a single definition of each container, such as vector, but we can define many different
kinds of vectors for example, vector <int> or vector <string>.

Function Templates
Program :
#include<iostream>
using namespace std;
template <class t>
t sum(t a,t b){
return a+b;
}
int main(){
cout<<sum(5,6.5);
}

Program :Array in Function Templates


#include<iostream>

using namespace std;

137
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

template <class t>


t sum(t a[],int size){
t s=0;
for(int i=0;i<size;i++){
s=s+a[i];
}
return s;
}
int main(){
int a[5]={1,2,3,4,5};
cout<<sum(a,5);
}

Program :Function Templates with different arguments


#include<iostream>
using namespace std;
template <class t, class t1>
t1 sum(t1 a, t b)
{
return a+b;
}
main()
{
float x;
int y;
cout<<"enter two values\n";

138
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

cin>>x>>y;
cout<<sum(x,y);
}

Program :

#include <iostream>
#include <string>

using namespace std;

template <typename T>


inline T const& Max (T const& a, T const& b) {
return a < b ? b:a;
}

int main () {
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;

double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;

string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;

139
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

return 0;
}

Program : Function overloading in Templates


#include<iostream>
using namespace std;
template <class t>
t sum(t a,t b){
return a+b;
}
template <class t>
t sum(t a,t b,t c){

return a+b+c;
}
int main(){
cout<<sum(6,6)<<endl;
cout<<sum(6.6,6.6,6.6);

Class Template
Just as we can define function templates, we can also define class templates. The
general form of a generic class declaration is shown here −
template <class type> class class-name {

140
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is
instantiated. You can define more than one generic data type by using a comma-
separated list.

Program :
#include<iostream>
using namespace std;
template <class t>
class student{
t a, b;
public:
void name(t a1,t b1){
a=a1;
b=b1;
}
void display(){
cout<<a<<" "<<b;
}
t sum();

//if outside the class then we template syntax line again and then call function
//template<class t>
//t classname<t>::functionname()

141
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

};
template <class t>
t student<t>::sum()
{

return a+b;
}
int main(){
student <int> s;
s.name(5,6);
s.display();
cout<< s.sum();
}

Program :
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>


class Stack {
private:

142
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

vector<T> elems; // elements

public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element

bool empty() const { // return true if empty.


return elems.empty();
}
};

template <class T>


void Stack<T>::push (T const& elem) {
// append copy of passed element
elems.push_back(elem);
}

template <class T>


void Stack<T>::pop () {
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}

// remove last element


elems.pop_back();
143
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

}
template <class T>
T Stack<T>::top () const {

if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}

int main() {
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings

// manipulate int stack


intStack.push(7);
cout << intStack.top() <<endl;

// manipulate string stack


stringStack.push("hello");
cout << stringStack.top() << std::endl;

144
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU

stringStack.pop();
stringStack.pop();
} catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}

145

You might also like