Professional Documents
Culture Documents
OOP Lab Manuall
OOP Lab Manuall
OOP Lab Manuall
LAB MANUAL
1
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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.
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.
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
3 Call by Reference
2
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
Program :
#include <iostream>
// function declaration
int main () {
int a = 100;
int b = 200;
int ret;
return 0;
3
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
int result;
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 −
Task#2:
#include <iostream>
4
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
int result;
result = a + b;
return (result);
int main () {
int a = 100;
int b = 200;
int result;
result = sum(a);
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 −
Program :
#include <iostream>
/* Function declaration */
int main()
int s, e;
cin>>s;
cin>>e;
printNaturalNumbers(s, e);
6
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
return 0;
/* Function definition */
cout<<start<< end;
cout<<start;
start++;
Output -
5, 6, 7, 8, 9, 10,
/**
7
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
*/
#include <iostream>
/* Function declaration */
int randPrime();
int main()
int 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)
isPrime = 1;
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 -
41
491
14771
25667
28703
/**
*/
#include <iostream>
10
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
/* Function declaration */
int main()
cin>>num);
/* Function call */
isEven = evenOdd(num);
if(isEven == 0)
else
return 0;
/* Function definition */
11
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
if(num % 2 == 0)
return 0;
else
return 1;
Output -
Enter a number: 5
/**
* 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
c = cube(num);
return 0;
}
/**
* Function to find cube of any number
*/
double cube(double num)
{
return (num * num * num);
}
Program
#include <iostream>
#include <cmath>
int main()
13
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
cout << base << "^" << exponent << " = " << result;
return 0;
Output
4.5
2.3^4.5 = 42.44
14
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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
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
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:
16
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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.
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:
18
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
1 Null Pointers
2 Pointer Arithmetic
3 Pointers vs Arrays
4 Array of Pointers
5 Pointer to Pointer
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;
}
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
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,
Program:
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
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>
struct Distance
int feet;
float inch;
};
int main()
Distance *ptr, d;
ptr = &d;
25
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";
return 0;
#include <iostream>
int main()
return 0; }
#include <iostream>
int main()
char arr[20];
26
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
int i;
*(arr + i) = 65 + i;
*(arr + i) = '\0';
return(0);
#include <iostream>
int main()
char *ptr;
ptr = Str;
ptr += 5;
return 0;
27
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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 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
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
#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;
#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
#include<iostream>
#include<conio.h>
getch();
return 0;
32
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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;
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;
#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;
36
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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
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 −
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;
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;
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
………………………………………………………………………………………………
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
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
……………………………………………………………………………………………………
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
return 0;
}
45
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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;
}
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
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;
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;
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;
//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;
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;
}
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
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
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);}
};
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
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;
};
return 0;
59
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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
60
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
Program :
#include <iostream>
class Line {
public:
private:
double length;
};
cout << "Object is being created, length = " << len << endl;
length = len;
61
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
length = len;
return length;
int main() {
Line line(10.0);
line.setLength(6.0);
62
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
return 0;
following result −
Length of line : 10
Length of line : 6
Objective(s):
63
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
object of it's class goes out of scope or whenever the delete expression is applied to a
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>
class Line {
public:
private:
double length;
};
Line::Line(void) {
Line::~Line(void) {
length = len;
return length;
65
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
int main() {
Line line;
line.setLength(6.0);
return 0;
following result −
Length of line : 6
Copy Constructor
66
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
Program
#include<iostream>
#include<cstring>
class test{
int code;
float price;
public:
void disp();
};
code=c;
price=p;
67
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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;
t1.disp();
t2.disp();
68
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
t3.disp();
return 0;
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;
}
~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
};
return 0;
}
Program :
#include<iostream>
72
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
#include<cstring>
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;
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
Introduction to Inheritance
Objective(s):
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
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 −
Program :
#include <iostream>
// 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
public:
int getArea() {
};
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);
return 0;
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
Total area: 35
-----------------------------------------------------------------------------------
78
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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 −
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.
79
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
Multiple Inheritance
A C++ class can inherit members from more than one class and here is the extended
syntax −
Program :
#include <iostream>
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;
};
class PaintCost {
public:
};
// Derived class
public:
int getArea() {
81
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
};
int main(void) {
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
82
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
Total area: 35
-----------------------------------------------------------------------------------
83
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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>
//base class
class animal {
protected:
int legs;
string hair;
public:
84
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
legs=a;
hair=b;
};
//child class
protected :
string color;
public:
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
};
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
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.
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;
}
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;
public:
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;
~Course()
{
cout<<"Course:dtor\n";
delete (courseName_p);
};
91
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
int main()
{
int i;
cout<<"\n";
92
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
cout<<"\n";
cout<<"\n";
cout<<"\n";
cout<<"Deletion of objects...\n\n";
cout<<"\n";
93
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
delete departNames[i];
}
cout<<"\n";
return(0);
}
output:
------
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
Deletion of objects...
Student::dtor
Student::dtor
Student::dtor
Student::dtor
Department::dtor
Department::dtor
Course:dtor
Course:dtor
Course:dtor
Course:dtor
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->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;
}
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:
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.
Program :
#include<iostream.h>
class House;
class Room
{
public:
100
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
Room()
{
};
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";
}
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
Room::initList_v(roomsList_p);
Room* myRoom;
Room::createRoom_v(myRoom, this, "Kitchen");
roomsList_p[0] = myRoom;
~House()
{
cout<<"House:dtor\n";
unsigned int 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<<"\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
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();
}-------------------------------------------------------------------------------------------------------------
108
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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 );
};
110
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
box.setWidth(10.0);
return 0;
}
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
112
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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();
};
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;
}
115
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
};
int main() {
Distance D1(11, 10), D2(-5, 11);
return 0;
}
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11
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
119
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
// 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;
// volume of box 3
volume = Box3.getVolume();
120
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
return 0;
}
121
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
int id;
string name;
public :
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
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;
}
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
126
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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
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();
};
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; }
};
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= ▭// 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';
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;
}
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.
Program :
// CPP program to illustrate
#include<iostream>
class base
133
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
public:
void show ()
};
public:
void print ()
void show ()
};
int main()
base *bptr;
derived d;
bptr = &d;
134
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
bptr->print();
bptr->show();
Program 2 :
#include<iostream>
class A{
public:
};
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
};
class C:public A{
private:
int val2;
public:
C(int x){
val2= x;
void disp(){
};
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
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);
}
137
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
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>
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;
}
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>
142
Data structures and algorithms Lab manual for BSCS/MCS
Department of CS, LGU
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
}
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
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