Beruflich Dokumente
Kultur Dokumente
0
Prepared by LE Arshia Arif
PRACTICAL HANDOUTS
EC-204 DATA STRUCTURES
&
OBJECT ORIENTED PROGRAMMING
It is the responsibility of the student to logout, Shutdown after using the computer.
Do not change internet IP Address, it can cause conflict on the network.
Please do not save your data on C: Drive.
Do not plug in external devices without scanning them.
Avoid stepping on electrical wires or any other computer cables.
Do not remove any device from the lab without permission.
Try not to type continuously for extremely long period, look away from the screen for a
while to give your eyes a rest.
In case of any hazard immediately switch off main supply and inform the lab staff.
Smoke detector and Alarming systems are installed in the lab.
In case of fire shout loudly fire, fire and use emergency doors for evacuation.
Never eat, drink or smoke while working in the laboratory.
If a piece of equipment fails while being used, report it immediately to your lab staff or
tutor.
Never try to fix the problem yourself because you could harm yourself and others.
CONTENTS
Ref: https://www.tutorialspoint.com/cplusplus
Lab Number 01
Introduction to MinGW
&
Compiling a C++ program
Objective
Objective of this lab is to learn about:
MinGW
Compiling a C++ Program
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
What is MINGW?
Learn about MinGW using the following link. You will also know how to install it. It is very easy, just
follow the steps.
1 - http://www.mingw.org/wiki/Getting_Started
2 - http://www.mingw.org/wiki/HOWTO
MINGW is a GCC compiler for Windows. MSYS is a collection of GNU utilities such as bash, make, gawk
and grep to allow building of applications and programs which depend on traditionally UNIX tools to be
present. It is intended to supplement MinGW and the deficiencies of the cmd shell. While, MinGW
("Minimalistic GNU for Windows") is a collection of freely available and freely distributable Windows
specific header files and import libraries combined with GNU toolsets that allow one to produce native
Windows programs that do not rely on any 3rd-party C runtime DLLs.
MINGW Installation
An automated GUI installer assistant called mingw-get-setup.exe is the preferred method for first time
installation. This will guide you through the setup of the mingw-get installer proper; you will then use
this to perform further package installations, and to manage your installation.
Regardless of how you installed MinGW and/or MSYS, if you did choose to install MSYS, you should
check its configuration. You need to ensure that MSYS knows where MinGW is located, so:
1. Open a Windows Explorer window and locate your installation directory (i.e. C:\MinGW, or
any alternative you nominated during installation).
2. Below your installation directory, you should find a directory named "msys", (normally in
lower case letters, but mixed case, or all upper case is okay too); open this then find and open
the additional subdirectories, "1.0" and "etc".
3. Within the "etc" directory, there should be a file named "fstab"; (if not, create one, as a new
text file). Open this with a text editor; (you should be able to do this by right clicking on it, and
in the popup menu select "Open" or "Open With", although you may find that you need to
select a suitable editor application to do so).
4. Edit the file and ensure that it contains one line, (there may be others), which reads:
C:\MinGW /mingw
(substituting the FULL ABSOLUTE path of any alternative to C:\MinGW, which you nominated
during installation); ensure that you follow this path name entry with at least one space, or tab,
before typing the "/mingw" entry.
5. Before you save the file, ensure that there is at least one blank line at the bottom, below all of
the entries that may exist, then save and close the file.
6. Additionally, if you have installed MSYS, you are advised to create a start menu "MinGW
Shell" shortcut in your "Start\Programs\MinGW" folder, (which you may also need to create);
this should invoke the C:\MinGW\msys\1.0\msys.bat script, which is installed as a component
of MSYS; (if you installed to an alternative directory, you should adjust the C:\MinGW prefix
accordingly). Double clicking this shortcut will then open a command window with the correct
environment set up for you, including the correct path references, allowing you to run any of
the MinGW or MSYS applications within that command window.
7. Your MinGW and MSYS installations should now be ready for use.
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
Example:
For the file helloworld.cpp in the folder C:\sources\hello enter the commands
cd c:\sources\hello
the -o switch specifies the name of the output file, without it the output file would be given a default
name of "a.exe".
If there are any errors in the source file the command line will notify you and direct you to the line
where the error is say you had forgotten to add an extra line at the end of your source file (an easy
mistake when moving from an environment such as Microsoft Visual C++) and you missed the ; at the
end of the last statement. You will get a message similar to this:
helloworld.cpp: In function 'int main()':
note: if your source is in C, rather than C++, your source files will be "helloworld.c", "foo.c", etc., and
you would use the "gcc" command, rather than the "g++" command; otherwise the procedure is
similar to the above.
Whilst still in the command prompt (and dircectory is still at the .exe's location) you can run your
program by typing the name of the executable file:
helloworld.exe
Objective:
Objective of this lab is to learn about:
Standard Input, Output
Handling IO Exceptions
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Standard output stream (cout): Usually the standard output device is the display screen. cout is
the instance of the ostream class. cout is used to produce output on the standard output device
which is usually the display screen. The data needed to be displayed on the screen is inserted in
the standard output stream (cout) using the insertion operator (<<).
Example:
#include <iostream>
int main( ) {
char sample[] = "Course";
cout << sample << " – Data Structures and Object Oriented
Programming";
return 0;
}
Run this code and write down your observations:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
Standard input stream (cin): Usually the input device is the keyboard. cin is the instance of the
class istream and is used to read input from the standard input device which is usually
keyboard.
The extraction operator (>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.
Example:
#include<iostream>
using namespace std;
int main()
{
int age;
return 0;
}
Run this code and write down your observations:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
Un-buffered standard error stream (cerr): cerr is the standard error stream which is used to
output the errors. This is also an instance of the ostream class. As cerr is un-buffered so it is
used when we need to display the error message immediately. It does not have any buffer to
store the error message and display later.
Example:
#include <iostream>
int main( )
{
cerr << "An error occured";
return 0;
}
Run this code and write down your observations:
________________________________________________________________________
________________________________________________________________________
_______________________________________________________________________
File Handling:
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created
for permanent storage of data.
To read and write from a file requires another standard C++ library called fstream, which defines two
stream classes:
• ofstream: Stream class to create files and to write information to files
• ifstream: Stream class to read information from files
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++
source file.
Opening a File:
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may
be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Syntax:
class_object.open(“file_name”);
Example:
ofstream myfile;
myfile.open ("example.txt");
Here myfile is the object of class ofstream. Now you can use the open() function through the object to
open a file.
Closing a File:
When a C++ program terminates it automatically flushes all the streams, release all the allocated
memory and close all the opened files. But it is always a good practice that a programmer should close
all the opened files before program termination.
Syntax:
class_object.close();
Example:
Myfile.close();
Here myfile is the object of any class and it has been used to call close() function to close the file.
Writing to a File:
While doing C++ programming, you write information to a file from your program using the stream
insertion operator (<<) just as you use that operator to output information to the screen. The only
difference is that you use an ofstream or fstream object instead of the cout object.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Run this code and write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Exception Handling:
In this topic we learn that how can we control run time error using exception handing in C++. Exception
provides a method to control exceptional conditions (like run time error) or to control any crashed
program by transferring control to some special functions called handler.
We can use following the keywords or functions to control runtime error in C++:
1. try {}
2. catch {}
3. throw()
Try{} block:
This block captures series of errors in any program at runtime and throws them to the catch block
where user can customize the error message. It represents a block of code that can throw an exception.
Syntax:
try
{
//define program;
throw(variable);
}
catch {} Block:
This block catches the error thrown by try block. This block contains method to customize error. It
represents a block of code that is executed when a particular exception is thrown.
Syntax:
catch
{
//defines method to control error;
}
throw function
This function is used to transfer the error from try block to catch block. This function plays major role to
save program from crashing.
Syntax:
throw(variable);
Example 1:
#include<iostream>
using namespace std;
int main()
{
try
{
throw(55); //Here we input integer value;
}
catch(int e) //This catch takes int value;
{
return 0;
}
Try to run this code with throw(55.5) and throw (‘I’) too. Write down your outputs with your
observations:
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_______________________________________________________________________________________________________
int main()
{
try {
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
Objective
Objective of this lab is to learn about:
Recursion
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Recursion:
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.
Syntax:
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function; otherwise it will go into
an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.
Example (Factorial)
#include <stdio.h>
#include <iostream>
using namespace std;
3) We can dynamically allocate storage space while the program is running, but we cannot create new
variable names "on the fly"
For this reason, dynamic allocation requires two steps:
1. Creating the dynamic space.
2. Storing its address in a pointer (so that the space can be accesed)
To dynamically allocate memory in C++, we use the new operator.
Allocation is done by keyword new
int* ptr = new int;
int* ptr = new int[];
4) De-allocation:
Deallocation is the "clean-up" of space being used for variables or other data storage
Compile time variables are automatically deallocated based on their known extent (this is the
same as scope for "automatic" variables)
It is the programmer's job to deallocate dynamically created space
To de-allocate dynamic memory, we use the delete operator
Example 1(DMA)
#include <iostream>
using namespace std;
int main()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 29494.99; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue; // free up the memory.
return 0;
}
Run this Code and write down the output along with your observations:
_________________________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________
Example 2(DMA)
//dynamic allocation
#include<iostream>
using namespace std;
int main()
{
int* ptr = new int;
*ptr = 2;
*ptr = *ptr * 4;
cout << "Data at memory is " << *ptr << endl;
delete ptr;
ptr = NULL;
return 0;
}
Run this Code and write down the output along with your observations:
_________________________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________
Objective
Objective of this lab is to learn about:
Pointers
Structures (Self Referential)
Linked List
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Run this code and write down its output with your observations:
__________________________________________________________
__________________________________________________________
_______________________________________________________
Pointers:
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.
The general form of a pointer variable declaration is –
Data_type *variable_name;
Here, Data_type is the pointer's base type; it must be a valid C++ type and variable_name is the
name of the pointer variable.
“*” is used before variable name to declare a pointer.
Examples:
int * ip; // pointer to an integer
char *cp; // pointer to a character
double*dp; //pointer to a double type variable
Initializing a pointer:
We initialize a pointer by address of some type of variable.
Example:
int a=24;
int *ptr=&a;
It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is
called a null pointer.
Example:
Int *ptr=NULL;
Dereferencing:
Dereferencing is to access the value at the address available in the pointer variable. This is done by using
unary operator * that returns the value of the variable located at the address specified by its operand.
Example:
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << var << endl;
cout << ip << endl;
cout << *ip << endl;
return 0;
}
Run this code. Write down its output with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
• Incrementing a Pointer:
Example:
int arr[3]={1,2,3};
int*ptr=arr; // pointing to first index of the array
ptr++; // pointing to the 2nd index of the array ptr++=ptr+1
Examples:
Code 1:
#include<iostream>
using namespace std;
int main()
{
int arr[5] = { 1,2,3,4,5 };
//int*ptr;
//ptr = arr;
}
Code 2:
#include<iostream>
using namespace std;
int main()
{
int arr[5] = { 1,2,3,4,5 };
int*ptr;
ptr = arr;
for (int i = 0; i < 5; i++)
{
cout << "Value of arr[" << i << "] = ";
cout << *(ptr+i) << endl;
}
system("pause");
return 0;
}
Run Code 1 and code 2 and compare the outputs of both. Write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Structures:
A number of data items of different types grouped together.
They store related information, not necessarily of the same data-type.
Example: Students
All the students have related information, such as their student ids, the courses taken and their
ages.
Even though all this information is related to one student, the data-types are different.
How to use:
In your main, you can use them as variables
Student a, b;
a.name = "Usama";
b.name = "Ammar Ali";
cout << a.name << endl << b.name << endl;
Structure Variables:
Structure variables are declared like variables of other types. The following declarations
struct student data; // or student data
struct student body[ 52 ]; // or student body[52]
struct student *sPtr; // or student * sPtr;
declare data to be a structure variable of type student, body to be an array with 52 elements of type
student and sPtr to be a pointer to a Student structure
Example:
struct Date
{
int day;
int month;
int year;
};
int main()
{
Date d;
d.day = 12;
d.month = 9;
d.year = 2007;
}
Self-Referential structures:
A structured data type which can point same data type.
Example:
struct node
{
Int data; //Data at this node
Node *next; //Pointer to next
};
Example:
int main()
{
node *p, *q ;//pointers to node
p = new node;//dynamic allocation
q = new node;
//linking two variables to form list
p -> data = 52;
p -> next = q;
q -> data = 26;
q -> next = NULL;
cout << p->data; //52
cout << p->next->data; //26
return 0;
}
Run this code and write down your output:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
Linked List:
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at
contiguous location; the elements are linked using pointers.
In C++, we can represent a node using structures. Below is an example of a linked list node with an
integer data.
Example:
struct node
{
int val;
node *ptr;
};
Val 1
N
1. Point the new node’s pointer to the already present 1st node of the linked list.
2. Point the head to the new node being inserted.
3. Insert the value as data in the new node.
Insertion at end:
HEA
D
Val
1. Get the value and position as input arguments of the function.
2. Create a temporary node type pointer and traverse it till the position of insertion.
3. Create a new node “N” which is to be inserted.
4. Now point its pointer to the next node at (position+1) location.
5. Update the pointer of previous node and point it to the new node.
6. Insert the value in the new node too.
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Class:
A class is an expanded concept of C structure: instead of holding only data, it can hold both data and
functions. (now C structs can have functions too but everything is “public” in structs)
The fundamental idea is to combine into a single unit both data and functions that operate on the data.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object
would be the variable
Syntax:
class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
};
Access Specifiers:
An access specifier is one of the following three keywords:
Private
Public
Protected
These specifiers modify the access rights that the members following them acquire
Example:
Constructor:
Destructor:
Destructor functions are the inverse of constructor functions.
As constructors, destructor functions are also called automatically when an object is destroyed
Same name as the class, preceded by tilde(~)
No return values and No arguments
The most common use of destructors is to de-allocate memory that was allocated for the object.
Should be used before object goes out of scope
Example:
Objects:
To use a class in a C++ program, its objects must be instantiated
Similar to declaring a variable
Example:
Data Encapsulation:
All C++ programs are composed of the following two fundamental elements −
Program statements (code) − This is the part of a program that performs actions and they are
called functions.
Program data − The data is the information of the program which gets affected by the program
functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions
that manipulate the data, and that keeps both safe from outside interference and misuse. Data
encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and data
abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from
the user.
C++ supports the properties of encapsulation and data hiding through the creation of user-defined
types, called classes. We already have studied that a class can contain private,
protected and public members. By default, all items defined in a class are private.
Example:
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
Run this code and write down the output along with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
The private member total is something that is hidden from the outside world, but is needed for the class
to operate properly.
Objective:
Objective of this lab is to learn about:
Linked List
Node Insertion
Node Deletion
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from
another block
Spaghetti code and confusing code is not acceptable
Linked List:
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at
contiguous location; the elements are linked using pointers.
In C++, we can represent a node using structures. Below is an example of a linked list node with an
integer data.
Example:
struct node
{
int val;
node *ptr;
};
The Pseudo codes for the above mentioned functions are given below:
Insertion at Start:
Head
2
N
Val 1
1. Point the new node’s pointer to the already present 1st node of the linked list.
2. Point the head to the new node being inserted.
3. Insert the value as data in the new node.
Insertion at end:
HEA
D
2
HEAD
1
TEMP
1
1. Create two new node type pointers, “Current” and “Previous”.
2. Traverse “Current” till specified Position and “Previous” till (Position-1) location.
3. Update the pointer of “Previous” and point it to the node next to “Current”.
4. Delete the “Current” node.
Traversal:
HEAD
Objective:
Objective of this lab is to learn about:
Stacks
Queues
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Stacks:
Stack is a linear data structure which follows a particular order in which the operations are performed.
The order should be LIFO(Last In First Out)
Mainly the following three basic operations are performed in the stack:
Push(data): Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
Pop(): Removes an item from the stack. The items are popped in the reversed order in which they
are pushed. If the stack is empty, then it is said to be an Underflow condition.
GetPeek() or GetTop(): Returns top element of stack.
isEmpty(): Returns true if stack is empty, else false.
Example:
There are many real life examples of stack. Consider the simple example of plates stacked over one
another in canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has
been placed at the bottommost position remains in the stack for the longest period of time. So, it can be
simply seen to follow LIFO order.
Implementation:
There are two ways to implement a stack:
Using array
Using linked list
What we have done so far is nothing different from stacks. We have done insertion of the data in the list
from one side only and removal of the data from the same side too. This exactly is the stack. We use
"Push" for inserting an element and "Pop" for removing an element but in case of stacks the "popped"
element is usually useful so we do return this to main.
QUEUES:
Queue is an abstract data structure used for storing homogeneous data in an order. Unlike stacks, a
queue is open at both ends. One end is always used to insert data called Rear and the other is used to
remove or access data called Front of the queue. It follows First-In-First-Out (FIFO) methodology i.e.
the data item inserted first will be accessed first.
Queue Representation
The following diagram given below tries to explain queue representation as data structure
Like stacks a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures.
Basic Operations
Queue operations involve initializing or defining the queue, utilizing it, and then completely erasing it
from the memory. Given below are the basic functions associated with queues
enqueue()
dequeue()
GetFront()
isfull()
isempty()
Size()
Create ()
Destroy()
Enqueue: This function is used to insert a data element in the queue. As queue has both ends open so
they maintain two data pointers front and rear. Add data element to the queue location, where the rear
is pointing.
Dequeue: Accessing data from the queue is a process of two tasks − access the data where front is
pointing and remove the data after access
In queue, we always dequeue or access data by using front pointer whereas rear pointer is used to
enqueue (or store) data.
GetFront: This function is used to get the data value present at the front of queue.
Isfull: It checks if the queue is full. It is useful when single dimension array is used to implement queue.
Here we just check for the rear pointer to reach at maximum size to determine that the queue is full.
Isempty: It checks if the queue is empty or not. If the value of front is less than MIN or 0, it tells that the
queue is not yet initialized, hence empty.
Size: This function returns the size of queue
Create: It creates a new queue by initializing variables and allocating space.
Destroy: It deletes the present queue.
Write down two applications of
Stacks
Queues
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Inheritance:
A form of software reuse in which you create a class that absorbs an existing class’s data and
behavior and enhances them with new capabilities.
In inheritance, a class derives the behavior and structure of another (existing) class.
Example: Inheritance Hierarchy for University Community Member
Community Member
Single
Employee Student Alumnus Inheritance
Single
Faculty Staff Inheritance
Single
Teacher Administrator Inheritance
Multiple
Administrator Teacher Inheritance
Practical Meaning of Inheritance:
Data members in the parent are part of the child
Behavior defined in the parent are part of the child
Note that private aspects of the parent are part of the child, but are not (directly)
accessible within the child class
Syntax:
class DerivedClass : kind BaseClass
where,
kind is one of public, private or protected.
Advantages of Inheritance:
Saves time
Reuse of proven, debugged, high quality software
Kinds of Inheritance:
Public (Commonly used)
Public and protected members of the base class remain, respectively, public and protected
members of the derived class.
Protected
Public and protected members (described later) of the base class are inherited as protected
members of the derived class.
Private
Public and protected members of the base class are inherited as private members of the
derived class.
In all cases, private members of a base class remain private to the base class and cannot be
accessed directly by a derived class.
Access Specifiers:
Overloading Functions:
Same function name is given to different function
Differ point:
a. The number of parameters
b. The data type of parameters
c. The order of appearance
Example:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
Overriding Functions:
If derived class defines same function as defined in its base class, it is known as function
overriding in C++.
Uses same method name and same type signature.
Used by a child class to change behavior it inherited from its parent.
Inheritance is compulsory.
Must have exactly the same declaration in both base and derived class
Example:
Construct a complete program to run these overridden functions and write down your output
with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Virtual Functions:
Virtual functions are a type of dynamic polymorphism. A virtual function has following
properties:
It uses pointer
• Compiler performs late binding/run time binding/dynamic binding on this function.
• Compiler gives preference to address in pointer.
Example:
#include<iostream>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
void show ()
{ cout<< "show derived class" <<endl; }
};
int main()
{
base *bptr;
derived d;
bptr = &d;
Run this code and write your output with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Objective:
Objective of this lab is to learn about:
Operator Overloading
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Introduction:
In this lab session, we will practice how a mathematical operator like +,-,/ and * can defined between
two objects of some newly defined data types through classes. Previously we have been making
functions like add() and display() but now we will replace them with Operator + and Operator <<
respectively.
Operator Overloading
Operator Overloading is all about defining the functions of a specific mathematical operator between
two objects of some class.
Syntax:
returntype operator<sign> (parameters)
It is important to understand that
1. LHS - object for which member function is called
2. RHS – argument
Example 1:
Let’s implement a simple example Complex variable.
Run this code and write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
The new thing in this example is Copy Constructor. Copy Constructor, like initializing constructor,
initializes a newly defined object of class to the values already held by another object. So, after c2, is
created in memory, it will get the same data as c1 has.
You must have so many questions about the above function but for now, you just need to understand
the concept that insertion operator can be defined for any class.
Try this and write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
_____________________
Objective:
Objective of this lab is to learn about:
Templates
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Introduction:
In this lab session, we will understand what templated functions and templated classes are, how they
can be used and what their advantages are.
Templates:
Templates are powerful features of C++ which allows you to write generic programs. In simple terms,
you can create a single function or a class to work with different data types using templates.
Templates are often used in larger codebase for the purpose of code reusability and flexibility of the
programs.
Function Templates
Class Templates
Function Templates
A function template works in a similar to a normal function, with one key difference.
A single function template can work with different data types at once but, a single normal function can
only work with one set of data types.
In the above code, T is a template argument that accepts different data types (int, float),
and typename is a keyword.
Example:
Class Templates
Like function templates, you can also create class templates for generic class operations.
Sometimes, you need a class implementation that is same for all classes, only the data types used are
different.
Normally, you would need to create a different class for each data type OR create different member
variables and functions within a single class.
However, class templates make it easy to reuse the same code for all data types.
In the above declaration, T is the template argument which is a placeholder for the data type used.
Inside the class body, a member variable var and a member function someOperation() are both of
type T.
Example:
Write down any two advantages of using templates:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Objective:
Objective of this lab is to learn about:
Abstract Classes and Interfaces
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
Virtual Function:
A virtual function a member function which is declared within base class and is re-defined (Overriden) by
derived class. When you refer to a derived class object using a pointer or a reference to the base class,
you can call a virtual function for that object and execute the derived class’s version of the function.
Syntax:
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;
/* Other members */
};
Example:
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
Run this code and write down its output with your observations:
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
Abstract Class:
Sometimes implementation of all function cannot be provided in a base class because we don’t know
the implementation. Such a class is called abstract class.
For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape,
but we know every derived class must have implementation of draw(). Similarly an Animal class doesn’t
have implementation of move() (assuming that all animals move), but all animals must know how to
move. We cannot create objects of abstract classes.
Example:
In the following example, Test is an abstract class because it has a pure virtual function show().
// pure virtual functions make a class abstract
#include<iostream>
using namespace std;
class Test
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};
int main(void)
{
Test t;
return 0;
}
Run this code and write down your observations:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
class Base
{
public:
virtual void show() = 0;
};
int main(void)
{
Base *bp = new Derived();
bp->show();
return 0;
}
Run this code and write down its output with your observations :
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
3. If we do not override the pure virtual function in derived class, then derived class also becomes
abstract class.
Example:
The following example demonstrates the same.
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
int main(void)
{
Derived d;
return 0;
}
Run this code and write down your observations:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
4. An abstract class can have constructors.
Example:
#include<iostream>
using namespace std;
int main(void)
{
Derived d(4, 5);
d.fun();
return 0;
}
Run this code and write down its output with your observations:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Interface:
The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class
from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves
only as an interface.
An interface does not have implementation of any of its methods, it can be considered as a collection of
method declarations. In C++, an interface can be simulated by making all methods as pure virtual.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions,
which means that it supports the interface declared by the ABC. Failure to override a pure virtual
function in a derived class, then attempting to instantiate objects of that class, is a compilation error.
Objective
Objective of this lab is to learn about:
QT IDE
Step 14) Set project name and directory and then hit next
Step 15) Set Build System “qmake” and then hit next.
Step 16) Select Desktop Qt version MinGW 32 bit and hit next
Step 17) Then on Summary page click Finish
Step 18) Now your project is created and must look like this.
Step 19) Now can write any C++ code in main.cpp
Step 20) You can click on Debug button on the button left to switch to release mode.
Step 21) There will be 3 folders created. First(1) when you just created your project. Second(2) when you
run your code under Debug Setting. Third (3) when you run code under Release Setting.
Lab Number 13
Introduction to GUI
Application using QT
Objective
Objective of this lab is to learn about:
Gui Application using QT
Introduction
Qt is a cross-platform framework that can be used to create applications which incorporate rich
Graphical User Interfaces (GUIs). It consists of several libraries, of which Qt Core, Qt GUI, Qt Widgets are
used to design basic standalone desktop applications with GUIs.
To start writing applications, we require the Qt Software Development Kit (SDK), which bundles Qt
Modules, Qt Creator (IDE) and Qt Documentation in a single package, to be installed on our computer.
The resulting window contains a sidebar containing important controls, the file structure of the
project, a window showing open documents, and the color editor, as shown:
File Structure:
The file structure for our project contains the following:
HelloWorld.pro This is the Qt Project file containing information that allows Qt’s command-line
tool, QMake, to create ‘makefiles’ which are used by compilers to build the applications.
Headers This directory contains all the header files (.h) for the application.
Sources This directory contains all the source files (.cpp) for the application.
Forms This directory contains all the user interface files (.ui) for the application.
Like any CPP application, the starting point for our application is main.cpp, where an instance of
MainWindow object is created, defined in mainwindow.h file. The MainWindow ‘form’ is, hence, the
first screen our end-user sees.
The following main categories can be found in the Components window, positioned to the left of UI:
Layout Elements Allow the components to resize according to the user’s screen size.
Buttons Clickable entities that allow the user to invoke different actions.
Containers Components that enable us to organize other components on the UI better.
Input Widgets Allow the user to input dynamic data to the application.
Display Widgets Allow the application to display output to the user in a presentable manner.
To customize the UI, simply drag and position the different graphical components from the Components
Window onto the UI. Different aspects of each component can be altered from the Properties Window.
First Application:
Frontend
Backend:
Write the following code within void MainWindow::on_btn_showMessage_clicked() in the code editor:
Execution:
From the menu bar, click on Build > Run to run the application.
Lab Number 14
TREES
Objective:
Objective of this lab is to learn about:
Trees
1. Searching in a Tree
2. Insertion in a Tree
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from another block
Spaghetti code and confusing code is not acceptable
TREES:
In computer science, a tree is an abstract model of a hierarchical structure
A (general) tree is a collection of Nodes and edges such that
1. There is a single node from which paths to other nodes emerge; this node is called the root
2. There is a single, unique path to reach any node of the tree
Tree Terminologies:
Root: node without parent (A)
Siblings: Children of the Same parent
Internal node: node with at least one child, Non-leaf nodes are called internal nodes
(A, B, C, F)
Leaf (aka External node): node without children (E, I, J, K, G, H, D)
Depth of a node: number of ancestors
Height of a tree: maximum depth of any node (3)
If a tree is a collection of N nodes, then it has N-1 edges.
Binary tree
A finite set of elements that is either empty or is partitioned into three disjoint subsets.
The first subset contains a single element called the root of the tree
The other two subsets are themselves binary trees, called the left and right sub-trees of the
original tree
Each element of a binary tree is called a node
We call the children of an internal node left child and right child
Alternative recursive definition: a binary tree is either a tree consisting of a single node, or a tree
whose root has an ordered pair of children, each of which is a binary tree
Question:
Write down the pseudo Code to search a specific node in a tree.
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
Insertion:
To insert a new node following steps should be followed:
1. Create a new node
2. Check if the tree is empty
3. Otherwise traverse through the tree in such a way that
if the coming data is less than the root data then move to the left child
if the coming data is greater than the root data then move to the right child
else if the number matches the root data then the new node would not be inserted.
4. Traverse until you reach the leaf node.
5. Then insert the new node.
Example:
Question:
Write down the pseudo Code to insert a specific node in a tree.
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
Software Used:
Notepad++
Command Prompt
Important Notes
Use meaningful variable names
Indent your program so that statements inside a block can be distinguished from
another block
Spaghetti code and confusing code is not acceptable
TREES:
In computer science, a tree is an abstract model of a hierarchical structure
A (general) tree is a collection of Nodes and edges such that
1. There is a single node from which paths to other nodes emerge; this node is called the root
2. There is a single, unique path to reach any node of the tree
Tree Terminologies:
Root: node without parent (A)
Siblings: Children of the Same parent
Internal node: node with at least one child, Non-leaf nodes are called internal nodes
(A, B, C, F)
Leaf (aka External node): node without children (E, I, J, K, G, H, D)
Depth of a node: number of ancestors
Height of a tree: maximum depth of any node (3)
If a tree is a collection of N nodes, then it has N-1 edges.
Binary tree
A finite set of elements that is either empty or is partitioned into three disjoint subsets.
The first subset contains a single element called the root of the tree
The other two subsets are themselves binary trees, called the left and right sub-trees of the
original tree
Each element of a binary tree is called a node
We call the children of an internal node left child and right child
Alternative recursive definition: a binary tree is either a tree consisting of a single node, or a tree whose
root has an ordered pair of children, each of which is a binary tree
Example:
Deletion of Node with two Children:
1. Find a minimum value in the right subtree;
2. Replace value of the node to be removed with the found minimum. Now, right subtree contains
a duplicate!
3. Apply delete() to the right subtree to delete a duplicate.
Example:
Question:
Can you think of any other way to delete a node with two children?
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
Traversal:
When traversing any Binary Tree, the Algorithm has Three Choices of When to Visit a Node root:
Preorder Traversal
1) Visit the root
2) Traverse the Left subtree in Preorder
3) Traverse the Right subtree in Preorder
Inorder Traversal
1) Traverse the Left subtree in Inorder
2) Visit the root
3) Traverse the Right subtree in Inorder
Postorder Traversal
1) Traverse the Left subtree in Postorder
2) Traverse the Right subtree in Postorder
3) Visit the root
Example:
• Preorder traversal -- A B D H E I C F J K G
• Postorder traversal -- H D I E B J K F G C A
• In-order traversal -- D H B I E A J F K C G
Question:
Write down the pseudo code for inorder traversal through a binary search tree?
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
Objective:
In this lab you can work on your assigned course project. The project for the course is required to be
chosen after the first sessional exam. The guidelines are as follows:
Project Guidelines:
1. Students are allowed to choose the project on their own.
2. Project will be done in groups
3. The project group members should not be more than 2.
4. Project should not be related to banking and finance.
5. Project should be related to the fields of mechatronics, automation, gaming or embedded
systems.
6. The students can use any open source library for the project.
7. Project Code should be a C++ code.
8. OpenCV and OpeGLl projects are encouraged.
9. Students can choose from open source code, but code explanation, dataflow diagram and
flowcharts are required.
10. Three presentations will be held: Project defense, progress presentation and Final Presentation.
11. Deadlines for the project presentations will be conveyed soon.