OOP_LabManual_Fall24_IBIT | PDF | C++ | Class (Computer Programming)
0% found this document useful (0 votes)
4 views

OOP_LabManual_Fall24_IBIT

The document is a lab manual for the Object Oriented Programming course (IT 260) at the University of the Punjab, outlining a series of experiments and exercises related to C++ programming. It covers topics such as classes, objects, inheritance, polymorphism, and exception handling, along with practical coding examples and exercises. Additionally, it provides guidelines for using the Dev C++ IDE and criteria for evaluating programming assignments.

Uploaded by

saimnaeem9020
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

OOP_LabManual_Fall24_IBIT

The document is a lab manual for the Object Oriented Programming course (IT 260) at the University of the Punjab, outlining a series of experiments and exercises related to C++ programming. It covers topics such as classes, objects, inheritance, polymorphism, and exception handling, along with practical coding examples and exercises. Additionally, it provides guidelines for using the Dev C++ IDE and criteria for evaluating programming assignments.

Uploaded by

saimnaeem9020
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 143

IBIT – University of the Punjab OOP – LAB

Object Oriented Programming


Course Code IT 260

LAB MANUAL
IBIT – University of the Punjab OOP – LAB

List of Experiments:

Sr Description CLO Page


#

1 Exploring Dev-C++ IDE 1

2 Implementation of Classes & objects in C++ 2

3 Class constructor and destructor 2

4 Constant and non-constant function 2

5 Static data member and functions 2

6 Function overloading and Operator overloading 3

7 Unary & binary Operator Overloading 3

8 Inheritance & Polymorphism 3

9 Virtual Functions 3

10 Abstract classes 3

11 Interfaces 3

12 Streams and Files 3

13 Function Templates and Class Templates 4

14 Exception Handling 4

15 Open Ended Lab 4


IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Working with Dev C++: Edit, Compile and Run a C++ Program.
1.1 Objective:
1. Learn basic components of a C++ program.
2. Learn compilation process.
3. Learn how to use Dev C++.
4. Learn how to write, edit & run C++ Program.

1.2 Scope:
The student should know the following at the end of this lab:
1. Problem solving
2. How to install run and compile.
3. Basis structure of program
4. Writing Complete Programs

1.3 Useful Concepts:

C++ program:

A typical structure of a C++ program consists of:

 Pre-processor Directives that always begin with # (e.g. #include <iostream>)

o The two most frequent commands are #include and #define.


o #include command will include header files that have the definition of a function used
in the program like cout that is in iostream file.
o Note: #include <file> tells the compiler to look for file where system include files are
held
o #define is used to replace a text with a value, e.g. #define PI 3.141593

 Functions

A function is a block of statements that make a specific kind of processing. Every C++ program
has a main() function. The execution starts from main().

 Variables / identifiers

These are used to store data in a program. You must declare a variable before you use it.
IBIT – University of the Punjab OOP – LAB

Here is a general structure of a C++ program.

pre-processor #include <iostream>

directives main function using namespace std;

heading int main()

{ {

declarations cout<<“hello World”;

executable statements return 0;

} }
IBIT – University of the Punjab OOP – LAB

Download and Install Dev C++

1. Download Dev C++ from given link. http://www.bloodshed.net/dev/devcpp.html


2. Save it to your computer
3. Double Click the setup and you will see a following dialog box.
4. Select typical and click next
IBIT – University of the Punjab OOP – LAB

5. Select your destination folder and click install

6. Check Run Dev C++ and click finish.


IBIT – University of the Punjab OOP – LAB

7. Dev C++ first time configuration box will appear, click next and then ok.

8. Now your Dev C++ environment is ready to code.


IBIT – University of the Punjab OOP – LAB

9. Go to File in menu and select new then click project.

10. Write these lines of codes in your IDE.


IBIT – University of the Punjab OOP – LAB

11. Click Compile & Run from the menu item or the displayed icon.

12. If you did not have a syntax error on your code, you will get this output.
IBIT – University of the Punjab OOP – LAB

1.4 Exercises for lab


Exercise 1.1: Type and save the program with the name LAB0Q1.CPP

Exercise 1.2: Compile, Run, and Test the program

/* Volume of a sphere */
#include <iostream
> #include<cmath>
#define PI 3.14159
int main()
{
double radius, volume;
cout<<"enter the radius > ";
cin>>radius;
volume = 4.0 / 3.0 * PI * pow(radius,3);
cout<<"the radius of the sphere is :"<<
radius; cout<<"the volume of the sphere is
:"<< volume;
return 0;
}
1.5 Home Work
Launch Dev C++ in your computer and run the above programs
IBIT – University of the Punjab OOP – LAB

Criteria Description
Code
Implementation
Demonstrates a clear understanding of encapsulation, inheritance, and
polymorphism. Implements appropriate access specifiers and utilizes
1. Understanding of inheritance and polymorphism effectively. Utilizes OOP concepts to structure
OOP Principles the code logically.
Code is well-structured, organized, and easy to read. Includes
comments/documentation to explain complex sections, algorithms, and
2. Code Readability design decisions. Follows consistent naming conventions for variables,
and Documentation functions, and classes.
Demonstrates effective memory management practices, including dynamic
memory allocation and deallocation. Avoids memory leaks and dangling
3. Memory pointers by appropriately deallocating memory. Utilizes smart pointers or
Management other memory management techniques where applicable.
Implements robust error handling and exception mechanisms. Handles
exceptions gracefully without causing program termination or undefined
4. Exception behavior. Utilizes try-catch blocks where appropriate and provides
Handling informative error messages.
Utilizes standard library containers and algorithms effectively. Demonstrates
proficiency in utilizing standard library features for common tasks (e.g., file
5. Use of Standard I/O, string manipulation). Chooses appropriate data structures and
Library algorithms for specific tasks.
Problem-Solving
Skills
Designs efficient algorithms to solve given problems. Implements algorithms
using appropriate data structures and control flow constructs. Optimizes
6. Algorithm Design algorithms for performance and resource usage where necessary.
Demonstrates proficiency in debugging techniques. Effectively identifies and
7. Debugging and resolves logical errors, runtime errors, and segmentation faults. Utilizes
Troubleshooting debugging tools and techniques available in the development environment.
Designs comprehensive test cases to validate the functionality of the code.
8. Testing and Executes test cases systematically and identifies edge cases. Verifies the
Validation correctness of the implementation through rigorous testing.
Collaboration and
Communication
Collaborates effectively with team members in group projects. Contributes
9. Collaborative constructively to group discussions and problem-solving sessions. Shares
Skills knowledge and helps peers in understanding complex concepts.
Prepares clear and concise documentation for the codebase. Presents
10. Documentation findings, solutions, and project progress effectively in oral and written
and Presentation formats. Demonstrates professionalism and clarity in communication.
Criteria Description
Technical
Proficiency
1. Proficiency with
Tools and Demonstrates advanced proficiency in using laboratory tools and equipment
Equipment relevant to the subject matter.
2. Execution of Executes laboratory procedures with precision, accuracy, and minimal
Procedures supervision.
3. Troubleshooting Demonstrates adept troubleshooting skills to address unexpected issues or
Skills deviations during experiments.
IBIT – University of the Punjab OOP – LAB

Criteria Description
Experimental
Techniques
4. Experimental Designs experiments effectively, considering variables, controls, and
Design appropriate methods to achieve desired outcomes.
5. Data Collection Collects data meticulously, applies relevant statistical methods for analysis,
and Analysis and interprets results accurately.
Adheres strictly to laboratory safety protocols, ensuring a safe working
6. Laboratory Safety environment for oneself and others.
Critical Thinking and
Problem-Solving
7. Problem Identifies and articulates problems encountered during experiments,
Identification proposing potential solutions or troubleshooting strategies.
8. Adaptability and Demonstrates adaptability in response to changing experimental conditions
Flexibility or unforeseen challenges, adjusting procedures accordingly.
Communication and
Collaboration
9. Communication Communicates experimental procedures, observations, and results
Skills effectively, both verbally and in written reports.
Collaborates seamlessly with peers, sharing responsibilities, insights, and
10. Collaboration resources to accomplish common laboratory objectives.
Professionalism and
Ethics
Upholds ethical standards in research, ensuring honesty, integrity, and
11. Ethical Conduct respect for intellectual property and confidentiality.
12. Time Manages time efficiently to complete experiments within allocated
Management timeframes, meeting deadlines without compromising quality.
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Implementation of Classes & objects in C++

A program is a collection of small tasks that may depend on other tasks. You can use two
approaches to write a program in programming Fundamental but here you can you use class concept.

Class

In programming, a class is a blueprint for creating objects. It's a fundamental concept in object-
oriented programming (OOP) languages like C++, Java, Python, and many others. A class defines
the properties (attributes or data members) and behaviors (methods or member functions) that
objects of that class will have.

Object
In programming, an object is an instance of a class. It's a fundamental concept in object-oriented
programming (OOP) languages like C++, Java, Python, and many others. When you create an object
from a class, you're essentially creating a specific, unique copy of that class with its own set of data
values.
Objective(s):
The 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

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

Program
For finding max number
#include <iostream>
using namespace std;

class MaximumFinder {
public:
MaximumFinder(int num1, int num2) {
IBIT – University of the Punjab OOP – LAB

this->num1 = num1;
this->num2 = num2;
}

int findMax() {
return (num1 > num2) ? num1 : num2;
}

private:
int num1;
int num2;
};

int main () {
int a = 100;
int b = 200;
int ret;

MaximumFinder finder(a, b);

ret = finder.findMax();
cout << "Max value is : " << ret << endl;

return 0;
}

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

Max value is: 200

Program 2

Calculate sum of two numbers by using class

#include <iostream>

using namespace std;

class Calculator {

public:

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

return a + b;
IBIT – University of the Punjab OOP – LAB

};

int main () {

Calculator calc;

int a = 100;

int b = 200;

int result;

result = calc.sum(a, b);

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

result = calc.sum(a);

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

return 0;

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

Total value is :300

Total value is :120

Program :

#include <iostream>

using namespace std;

class NaturalNumbersPrinter {

public:

void printNaturalNumbers(int start, int end) {


IBIT – University of the Punjab OOP – LAB

cout << "Natural numbers between " << start << " and " << end << ": ";

while (start <= end) {

cout << start << " ";

start++;

cout << endl;

};

int main() {

int lowerRange, upperRange;

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

cin >> lowerRange;

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

cin >> upperRange;

// Creating an object of NaturalNumbersPrinter class

NaturalNumbersPrinter printer;

// Calling the method to print natural numbers

printer.printNaturalNumbers(lowerRange, upperRange);

return 0;

}Output -

Enter lower range to print natural numbers: 5


IBIT – University of the Punjab OOP – LAB

Enter upper limit to print natural numbers: 10

Natural numbers from 5 to 10 are:

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

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


each function call.

#include <iostream>

using namespace std;

class NaturalNumbersPrinter {

public:

// Method to print natural numbers within the specified range

void printNaturalNumbers(int start, int end) {

cout << "Natural numbers between " << start << " and " << end << ": ";

while (start <= end) {

cout << start << " ";

start++;

cout << endl;

};

int main() {

int lowerRange, upperRange;

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


IBIT – University of the Punjab OOP – LAB

cin >> lowerRange;

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

cin >> upperRange;

// Creating an object of NaturalNumbersPrinter class

NaturalNumbersPrinter printer;

// Calling the method to print natural numbers

printer.printNaturalNumbers(lowerRange, upperRange);

return 0;

Output -

Random 5 prime numbers are:

41

491

14771

25667

28703

Program: Write a C++ program to input a number and check the input is
even or odd. Define a function that accepts the number and return a
value 0 or 1. Return 0 if argument is even, otherwise return 1.

#include <iostream>

using namespace std;

class NumberChecker {
IBIT – University of the Punjab OOP – LAB

public:

int checkEvenOrOdd(int num) {

if (num % 2 == 0)

return 0; // Even

else

return 1; // Odd

};

int main() {

NumberChecker checker;

int num;

// Input number from the user

cout << "Enter a number: ";

cin >> num;

// Check if the number is even or odd

int result = checker.checkEvenOrOdd(num);

// Output the result

if (result == 0)

cout << "The number is even." << endl;

else

cout << "The number is odd." << endl;


IBIT – University of the Punjab OOP – LAB

return 0;

Output -

Enter a number: 5

The given number is ODD.

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


function.

#include <iostream>

using namespace std;

class CubeCalculator {

public:

// Method to calculate the cube of a number

int calculateCube(int num) {

return num * num * num;

};

int main() {

CubeCalculator calculator;

int num;

// Input number from the user


IBIT – University of the Punjab OOP – LAB

cout << "Enter a number: ";

cin >> num;

// Calculate the cube using the CubeCalculator object

int cube = calculator.calculateCube(num);

// Output the result

cout << "Cube of " << num << " is: " << cube << endl;

return 0;

Output

Enter base and exponent respectively: 2

2^4 = 16

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) {
IBIT – University of the Punjab OOP – LAB

width = x;
height = y;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}

When it compile its output be:


Area:12.

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;
IBIT – University of the Punjab OOP – LAB

cout << "rectb area: " << rectb.area() << endl;


return 0;
}
When it compile it output be:
rect area: 12
rectb area: 30

Program :

#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

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

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

// box 2 specification
Box2.height = 10.0;
IBIT – University of the Punjab OOP – LAB

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
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When this program is compile:


Volume of Box1:210
Volume of Box:1560
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

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.

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 :
IBIT – University of the Punjab OOP – LAB

#include <iostream>

using namespace std;

class Rectangle {

int width, height;

public:

Rectangle (int,int);

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

};

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

width = a;

height = b;

int main () {

Rectangle rect (3,4);

Rectangle rectb (5,6);

cout << "rect area: " << rect.area() << endl;

cout << "rectb area: " << rectb.area() << endl;

return 0;

When this program compile it will give :

Rect area:12

Rectb area:25

Program :

#include <iostream>

using namespace std;

class Circle {

double radius;

public:

Circle(double r) { radius = r; }

double circum() {return 2*radius*3.14159265;}


IBIT – University of the Punjab OOP – LAB

};

int main () {

Circle foo (10.0); // functional form

Circle bar = 20.0; // assignment init.

Circle baz {30.0}; // uniform init.

Circle qux = {40.0}; // POD-like

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

return 0;

When it compile it give:

Foos circumference:62.8319

The Class Constructor

A class constructor is a special member function of a class that is executed whenever we create new objects
of that class.

A constructor will have exact same name as the class and it does not have any return type at all, not even
void. Constructors can be very useful for setting initial values for certain member variables.

Following example explains the concept of constructor −

Task 4:

#include <iostream>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(); // This is the constructor

private:

double length;

};

// Member functions definitions including constructor

Line::Line(void) {
IBIT – University of the Punjab OOP – LAB

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

void Line::setLength( double len ) {

length = len;

double Line::getLength( void ) {

return length;

// Main function for the program

int main() {

Line line;

// set line length

line.setLength(6.0);

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

return 0;

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

Object is being created

Length of line : 6
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Parameterized Constructor
A default constructor does not have any parameter, but if you need, a constructor can have parameters. This
helps you to assign initial value to an object at the time of its creation as shown in the following example −

Program :

#include <iostream>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

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

private:

double length;

};

// Member functions definitions including constructor

Line::Line( double len) {

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

length = len;

void Line::setLength( double len ) {

length = len;

double Line::getLength( void ) {

return length;

// Main function for the program

int main() {

Line line(10.0);
IBIT – University of the Punjab OOP – LAB

// get initially set length.

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

// set line length again

line.setLength(6.0);

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

return 0;

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

Object is being created, length = 10

Length of line : 10

Length of line : 6
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

The Class Destructor


Objective(s):

A destructor is a special member function of a class that is executed whenever an object of it's class goes out
of scope or whenever the delete expression is applied to a pointer to the object of that class.

A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value
nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of
the program like closing files, releasing memories etc.

Tool(s) used:

Dev C++

Visual Studio

Program :

Following example explains the concept of destructor −

#include <iostream>

using namespace std;

class Line {

public:

void setLength( double len );

double getLength( void );

Line(); // This is the constructor declaration

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

private:

double length;

};

// Member functions definitions including constructor

Line::Line(void) {

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

Line::~Line(void) {
IBIT – University of the Punjab OOP – LAB

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

void Line::setLength( double len ) {

length = len;

double Line::getLength( void ) {

return length;

// Main function for the program

int main() {

Line line;

// set line length

line.setLength(6.0);

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

return 0;

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

Object is being created

Length of line : 6

Object is being deleted

Copy Constructor

Program

#include<iostream>

#include<cstring>

using namespace std;

class test{

int code;

float price;

public:
IBIT – University of the Punjab OOP – LAB

test(int c,float p);

test(const test &t);

void disp();

};

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

code=c;

price=p;

test :: test(const test &t){

code=t.code;

price=t.price;

void test::disp(){

cout<<code<<endl<<price;

int main(){

test t1(5,6.6);

test t2(t1);

test t3=t2;

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

t1.disp();

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

t2.disp();

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

t3.disp();

return 0;

}
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

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

Program:

#include <iostream>

using namespace std;

class student{

int id ;

float marks;

public:

student(){

cout<<"hello"<<endl;

student(int a){

id=a;

cout<<a<<endl;

student(int a, float b){

id=a;

marks =b;

cout<<"with two parameter "<<endl;

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

}
IBIT – University of the Punjab OOP – LAB

~student(){

cout<<"object is deleted"<<endl;

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;

};

// Member functions definitions including constructor

Line::Line(void) {

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


IBIT – University of the Punjab OOP – LAB

Line::~Line(void) {

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

void Line::setLength( double len ) {

length = len;

double Line::getLength( void ) {

return length;

// Main function for the program

int main() {

Line line;

// set line length

line.setLength(6.0);

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

return 0;

Program :

#include<iostream>

#include<cstring>

using namespace std;

class rectangle{

int length;

int height;

int width;

char name[10];

public:

rectangle()

length=10;
IBIT – University of the Punjab OOP – LAB

width=20;

height=30;

cout<<length<<endl<<height<<endl<<width<<endl<<endl;

rectangle(int len){

length=len;

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

rectangle(int len,int wid){

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);

Write a program to overload constructor and display date and time.


IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Constant and non-constant function


Program:
By using C++ pointer and const and non const function, 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.
Solution:
#include <iostream>
using namespace std;
class MaxFinder {
private:
const int* data;
int size;
public:
// Constructor
MaxFinder(const int* arr, int s) : data(arr), size(s) {}
// Non-const member function to find max value
int* findMax() {
int* maxPtr = const_cast<int*>(data);
for (int i = 1; i < size; ++i) {
if (*(data + i) > *maxPtr) {
maxPtr = const_cast<int*>(data + i);
}
}
return maxPtr;
}
// Const member function to display max value
void displayMax() const {
IBIT – University of the Punjab OOP – LAB

const int* maxPtr = findMax();


cout << "Max value in the data set: " << *maxPtr << endl;
}
};
int main() {
int n;
cout << "Enter the number of data values: ";
cin >> n;
int* data = new int[n];
cout << "Enter the data values: ";
for (int i = 0; i < n; ++i) {
cin >> data[i];
}
// Creating an object of MaxFinder class
MaxFinder maxFinder(data, n);
// Displaying the maximum value using the non-const member function
int* maxPtr = maxFinder.findMax();
cout << "Max value in the data set: " << *maxPtr << endl;
// Displaying the maximum value using the const member function
maxFinder.displayMax();
delete[] data;
return 0;
}

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


of the array in reverse order using a pointer.
Solution:
#include <iostream>
using namespace std;
class ArrayManipulator {
private:
IBIT – University of the Punjab OOP – LAB

const int* data;


int size;
public:
// Constructor
ArrayManipulator(const int* arr, int s) : data(arr), size(s) {}
// Non-const member function to print elements in reverse order
void printReverse() {
for (int i = size - 1; i >= 0; --i) {
cout << data[i] << " ";
}
cout << endl;
}
// Const member function to print elements in reverse order
void printReverse() const {
for (int i = size - 1; i >= 0; --i) {
cout << data[i] << " ";
}
cout << endl;
}
};

int main() {
int n;
cout << "Enter the number of data values: ";
cin >> n;
int* data = new int[n];
cout << "Enter the data values: ";
for (int i = 0; i < n; ++i) {
cin >> data[i];
}
IBIT – University of the Punjab OOP – LAB

// Creating an object of ArrayManipulator class


ArrayManipulator arrayManipulator(data, n);
// Printing elements in reverse order using non-const member function
cout << "Elements in reverse order (non-const function): ";
arrayManipulator.printReverse();
// Printing elements in reverse order using const member function
const ArrayManipulator constArrayManipulator(data, n);
cout << "Elements in reverse order (const function): ";
constArrayManipulator.printReverse();
delete[] data;
return 0;
}

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


keyword.
The five values will be stored in an array using a pointer. Then print the
elements of the array on the screen.
Solution:
#include <iostream>
using namespace std;
class ArrayPrinter {
private:
int* data;
const int size;
public:
// Constructor
ArrayPrinter() : size(5) {
data = new int[size];
}
// Destructor
~ArrayPrinter() {
IBIT – University of the Punjab OOP – LAB

delete[] data;
}
// Function to accept values from the user and store them in the array
void acceptValues() {
cout << "Enter five integer values:" << endl;
for (int i = 0; i < size; ++i) {
cin >> data[i];
}
}
// Non-const member function to print the elements of the array
void printElements() {
cout << "Elements of the array (non-const function): ";
for (int i = 0; i < size; ++i) {
cout << data[i] << " ";
}
cout << endl;
}
// Const member function to print the elements of the array
void printElements() const {
cout << "Elements of the array (const function): ";
for (int i = 0; i < size; ++i) {
cout << data[i] << " ";
}
cout << endl;
}
};
int main() {
// Creating an object of ArrayPrinter class
ArrayPrinter arrayPrinter;
// Accepting values from the user and storing them in the array
IBIT – University of the Punjab OOP – LAB

arrayPrinter.acceptValues();
// Printing elements of the array using the non-const member function
arrayPrinter.printElements();
// Printing elements of the array using the const member function
const ArrayPrinter constArrayPrinter = arrayPrinter;
constArrayPrinter.printElements();
return 0;
}

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


ascending order.
The function will accept two arguments-- a pointer that points to the
array and the array size. The function returns a pointer that points to the
sorted array.
Solution:
#include <iostream>
using namespace std;
class ArraySorter {
public:
// Non-const member function to sort the array in ascending order
int* sortArray(int* arr, int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
// Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
IBIT – University of the Punjab OOP – LAB

return arr;
}
// Const member function to sort the array in ascending order
const int* sortArray(const int* arr, int size) {
// Creating a copy of the array to avoid modifying the original array
int* sortedArray = new int[size];
for (int i = 0; i < size; ++i) {
sortedArray[i] = arr[i];
}
// Sorting the copied array
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (sortedArray[j] > sortedArray[j + 1]) {
// Swap elements if they are in the wrong order
int temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
}
}
}
return sortedArray;
}
};
int main() {
const int size = 10;
int arr[size] = {5, 2, 9, 1, 7, 3, 6, 8, 4, 10};
// Creating an object of ArraySorter class
ArraySorter arraySorter;
// Sorting the array using the non-const member function
int* sortedArray1 = arraySorter.sortArray(arr, size);
IBIT – University of the Punjab OOP – LAB

// Printing the sorted array


cout << "Sorted array (non-const function): ";
for (int i = 0; i < size; ++i) {
cout << sortedArray1[i] << " ";
}
cout << endl;
// Sorting the array using the const member function
const int* sortedArray2 = arraySorter.sortArray(arr, size);
// Printing the sorted array
cout << "Sorted array (const function): ";
for (int i = 0; i < size; ++i) {
cout << sortedArray2[i] << " ";
}
cout << endl;
// Freeing the dynamically allocated memory
delete[] sortedArray1;
delete[] sortedArray2;
return 0;
}

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


descending order.
#include <iostream>
using namespace std;

class ArraySorter {
public:
// Non-const member function to sort the array in descending order
int* sortArrayDescending(int* arr, int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
IBIT – University of the Punjab OOP – LAB

if (arr[j] < arr[j + 1]) {


// Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}

// Const member function to sort the array in descending order


const int* sortArrayDescending(const int* arr, int size) {
// Creating a copy of the array to avoid modifying the original array
int* sortedArray = new int[size];
for (int i = 0; i < size; ++i) {
sortedArray[i] = arr[i];
}

// Sorting the copied array in descending order


for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (sortedArray[j] < sortedArray[j + 1]) {
// Swap elements if they are in the wrong order
int temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
}
}
}
IBIT – University of the Punjab OOP – LAB

return sortedArray;
}
};

int main() {
const int size = 10;
int arr[size] = {5, 2, 9, 1, 7, 3, 6, 8, 4, 10};

// Creating an object of ArraySorter class


ArraySorter arraySorter;

// Sorting the array in descending order using the non-const member function
int* sortedArray1 = arraySorter.sortArrayDescending(arr, size);

// Printing the sorted array in descending order


cout << "Sorted array in descending order (non-const function): ";
for (int i = 0; i < size; ++i) {
cout << sortedArray1[i] << " ";
}
cout << endl;

// Sorting the array in descending order using the const member function
const int* sortedArray2 = arraySorter.sortArrayDescending(arr, size);

// Printing the sorted array in descending order


cout << "Sorted array in descending order (const function): ";
for (int i = 0; i < size; ++i) {
cout << sortedArray2[i] << " ";
}
IBIT – University of the Punjab OOP – LAB

cout << endl;


// Freeing the dynamically allocated memory
delete[] sortedArray1;
delete[] sortedArray2;
return 0;
}

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


keyword.
The five values will be stored in an array using a pointer. Then print the
elements of the array on the screen.
Solution:
#include <iostream>
using namespace std;

class ArrayPrinter {
private:
int* data;
const int size;

public:
// Constructor
ArrayPrinter() : size(5) {
data = new int[size];
}

// Destructor
~ArrayPrinter() {
delete[] data;
}
IBIT – University of the Punjab OOP – LAB

// Function to accept values from the user and store them in the array
void acceptValues() {
cout << "Enter five integer values:" << endl;
for (int i = 0; i < size; ++i) {
cin >> data[i];
}
}

// Non-const member function to print the elements of the array


void printElements() {
cout << "Elements of the array (non-const function): ";
for (int i = 0; i < size; ++i) {
cout << data[i] << " ";
}
cout << endl;
}

// Const member function to print the elements of the array


void printElements() const {
cout << "Elements of the array (const function): ";
for (int i = 0; i < size; ++i) {
cout << data[i] << " ";
}
cout << endl;
}
};

int main() {
// Creating an object of ArrayPrinter class
ArrayPrinter arrayPrinter;
IBIT – University of the Punjab OOP – LAB

// Accepting values from the user and storing them in the array
arrayPrinter.acceptValues();

// Printing elements of the array using the non-const member function


arrayPrinter.printElements();

// Printing elements of the array using the const member function


const ArrayPrinter constArrayPrinter = arrayPrinter;
constArrayPrinter.printElements();

return 0;
}

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


of the array in reverse order using a pointer.
Solution:
#include <iostream>
using namespace std;
class ArrayPrinter {
private:
int* data;
const int size;
public:
// Constructor
ArrayPrinter() : size(5) {
data = new int[size];
}

// Destructor
~ArrayPrinter() {
IBIT – University of the Punjab OOP – LAB

delete[] data;
}

// Function to accept values from the user and store them in the array
void acceptValues() {
cout << "Enter five integer values:" << endl;
for (int i = 0; i < size; ++i) {
cin >> data[i];
}
}

// Non-const member function to print the elements of the array in reverse order
void printReverse() {
cout << "Elements of the array in reverse order (non-const function): ";
for (int i = size - 1; i >= 0; --i) {
cout << data[i] << " ";
}
cout << endl;
}

// Const member function to print the elements of the array in reverse order
void printReverse() const {
cout << "Elements of the array in reverse order (const function): ";
for (int i = size - 1; i >= 0; --i) {
cout << data[i] << " ";
}
cout << endl;
}
};
IBIT – University of the Punjab OOP – LAB

int main() {
// Creating an object of ArrayPrinter class
ArrayPrinter arrayPrinter;

// Accepting values from the user and storing them in the array
arrayPrinter.acceptValues();

// Printing elements of the array in reverse order using the non-const member function
arrayPrinter.printReverse();

// Printing elements of the array in reverse order using the const member function
const ArrayPrinter constArrayPrinter = arrayPrinter;
constArrayPrinter.printReverse();

return 0;
}
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Static data member and functions


Objective(s):
The objective of Static data member and functions use some elements in fixed form which
cannot be changed and apply some function for better understanding.

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

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

class Book {
private:
static int nextId;
char title[50];
char author[50];
char subject[100];
int book_id;

public:
// Constructor
Book(const char* t, const char* a, const char* s) {
strcpy(title, t);
strcpy(author, a);
strcpy(subject, s);
book_id = nextId++;
IBIT – University of the Punjab OOP – LAB

// Static member function to reset the nextId


static void resetNextId() {
nextId = 1;
}

// Function to print book information


void printInfo() const {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Subject: " << subject << endl;
cout << "ID: " << book_id << endl;
}
};

// Initializing static member


int Book::nextId = 1;

int main() {
// Creating Book objects
Book book1("Learn C++ Programming", "Chand Miyan", "C++ Programming");
Book book2("Telecom Billing", "Yakit Singha", "Telecom");

// Print Book1 info


cout << "Book 1 Information:" << endl;
book1.printInfo();
cout << endl;

// Print Book2 info


IBIT – University of the Punjab OOP – LAB

cout << "Book 2 Information:" << endl;


book2.printInfo();
cout << endl;

// Resetting the nextId


Book::resetNextId();

return 0;
}
……………………………………………………………………………………………………

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

class Book {
private:
static int nextId;
char title[50];
char author[50];
char subject[100];
int book_id;

public:
// Constructor
Book(const char* t, const char* a, const char* s) {
strcpy(title, t);
strcpy(author, a);
strcpy(subject, s);
book_id = nextId++;
IBIT – University of the Punjab OOP – LAB

// Static member function to reset the nextId


static void resetNextId() {
nextId = 1;
}

// Function to print book information


void printInfo() const {
cout << "Book title: " << title << endl;
cout << "Book author: " << author << endl;
cout << "Book subject: " << subject << endl;
cout << "Book ID: " << book_id << endl;
}
};

// Initializing static member


int Book::nextId = 1;

int main() {
// Creating Book objects
Book book1("Learn C++ Programming", "Chand Miyan", "C++ Programming");
Book book2("Telecom Billing", "Yakit Singha", "Telecom");

// Print Book1 info


cout << "Book 1 Information:" << endl;
book1.printInfo();
cout << endl;

// Print Book2 info


IBIT – University of the Punjab OOP – LAB

cout << "Book 2 Information:" << endl;


book2.printInfo();
cout << endl;

// Resetting the nextId


Book::resetNextId();

return 0;
}
……………………………………………………………………………………………………
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Function overloading and Operator overloading


………………………………………………………………………………………………

Program
#include <iostream>
#include <cstring>
using namespace std;

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

// Function prototypes for function overloading


void printBook(const struct Books &book);
void printBook(const struct Books *book);

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

// Book 1 specification
strcpy(Book1.title, "Learn C++ Programming");
strcpy(Book1.author, "Chand Miyan");
strcpy(Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
IBIT – University of the Punjab OOP – LAB

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

// Print Book1 info using function overloading


printBook(Book1);

// Print Book2 info using function overloading


printBook(&Book2);

return 0;
}

// Function definition to print book information by passing structure by reference


void printBook(const 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;
}

// Function definition to print book information by passing structure by pointer


void printBook(const 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;
IBIT – University of the Punjab OOP – LAB

}
………………………………………………………………………………………………
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
Book id : 6495700
……………………………………………………………………………………………………

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

// Structure for address


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

// Base class Employee


class Employee {
protected:
int emp_id;
char name[50];
IBIT – University of the Punjab OOP – LAB

string designation;
Address address1;

public:
// Function to set employee details
void setDetails(int id, const char* n, const char* desig, int houseNo, const char* c, const
string& cntry) {
emp_id = id;
strcpy(name, n);
designation = desig;
address1.house_no = houseNo;
strcpy(address1.city, c);
address1.country = cntry;
}

// Overloaded function to print employee details


void printDetails() const {
cout << "Employee ID: " << emp_id << endl;
cout << "Name: " << name << endl;
cout << "Designation: " << designation << endl;
cout << "Address: " << address1.house_no << ", " << address1.city << ", " <<
address1.country << endl;
}

// Overloaded function with a different signature


void printDetails(int id) const {
cout << "Employee ID: " << id << endl;
cout << "Name: " << name << endl;
cout << "Designation: " << designation << endl;
cout << "Address: " << address1.house_no << ", " << address1.city << ", " <<
address1.country << endl;
IBIT – University of the Punjab OOP – LAB

}
};

// Derived class Manager


class Manager : public Employee {
public:
// Function overriding - prints manager's designation as "Manager"
void printDetails() const override {
cout << "Manager ID: " << emp_id << endl;
cout << "Name: " << name << endl;
cout << "Designation: Manager" << endl;
cout << "Address: " << address1.house_no << ", " << address1.city << ", " <<
address1.country << endl;
}
};

int main() {
// Creating an object of Employee
Employee emp;
emp.setDetails(2, "Ali", "Head", 5, "Lahore", "Pakistan");

// Printing employee details using overloaded function in the base class


emp.printDetails();
cout << endl;

// Printing employee details using the overloaded function with a different signature in the
base class
emp.printDetails(101);
cout << endl;

// Creating an object of Manager


IBIT – University of the Punjab OOP – LAB

Manager manager;
manager.setDetails(3, "John", "Manager", 10, "London", "UK");

// Printing manager details using overridden function in the derived class


manager.printDetails();

return 0;
}

Program
Function Overloading:
Area Calculated
#include <iostream>
using namespace std;
// Function to calculate the area of a square
int calculateArea(int side) {
return side * side;
}
// Overloaded function to calculate the area of a rectangle
int calculateArea(int length, int breadth) {
return length * breadth;
}
int main() {
cout << "Area of square: " << calculateArea(5) << endl;
cout << "Area of rectangle: " << calculateArea(4, 6) << endl;
return 0;
}

Sum of Numbers:
#include <iostream>
using namespace std;
IBIT – University of the Punjab OOP – LAB

// Function to calculate the sum of two integers


int sum(int a, int b) {
return a + b;
}
// Overloaded function to calculate the sum of three integers
int sum(int a, int b, int c) {
return a + b + c;
}

int main() {
cout << "Sum of two numbers: " << sum(5, 3) << endl;
cout << "Sum of three numbers: " << sum(4, 6, 2) << endl;
return 0;
}

Operator Overloading
Unary minus (-) operator overloading program in C++
/*C++ program for unary minus (-) operator overloading.*/
#include<iostream>
using namespace std;
class NUM
{
private:
int n;

public:
//function to get number
void getNum(int x)
{
n=x;
}
//function to display number
IBIT – University of the Punjab OOP – LAB

void dispNum(void)
{
cout << "value of n is: " << n;
}
//unary - operator overloading
void operator - (void)
{
n=-n;
}
};
int main()
{
NUM num;
num.getNum(10);
-num;
num.dispNum();
cout << endl;
return 0;

}
Unary increment (++) and decrement (--) operator overloading program in
C++
// C++ program for unary increment (++) and decrement (--) operator
overloading

#include <iostream>
using namespace std;
class NUM {
private:
int n;
public:
// function to get number
IBIT – University of the Punjab OOP – LAB

void getNum(int x)
{
n = x;
}
// function to display number
void dispNum(void)
{
cout << "value of n is: " << n;
}
// unary ++ operator overloading
void operator++(void)
{
n = ++n;
}
// unary -- operator overloading
void operator--(void)
{
n = --n;
}
};
int main()
{
NUM num;
num.getNum(10);
++num;
cout << "After increment - ";
num.dispNum();
cout << endl;
--num;
cout << "After decrement - ";
IBIT – University of the Punjab OOP – LAB

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

Program :
#include <iostream>
using namespace std;

class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
IBIT – University of the Punjab OOP – LAB

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

int main(void) {
printData pd;

// Call print to print integer


pd.print(5);

// Call print to print float


pd.print(500.263);

// Call print to print character


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

return 0;
}

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

class book{
public:
IBIT – University of the Punjab OOP – LAB

void print(){

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

void print(int a){

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

}
void print(string t){

//title=t;

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


}
void print(char c){

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

}
void print(int a,string s,char c){
//id=a;
// title=s;
//code=c;
cout<<"Book id is ="<<a<<endl;
IBIT – University of the Punjab OOP – LAB

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


cout<<"Book title is ="<<c<<endl
}
};

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

return 0;

}
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Introduction to Inheritance

Objective(s):
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.

When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of
an existing class. This existing class is called the base class, and the new class is
referred to as the derived class.

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

Dev C++

Visual Studio

Base and Derived Classes


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

class derived-class: access-specifier base-class

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


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

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

Program :
IBIT – University of the Punjab OOP – LAB

#include <iostream>

using namespace std;

// Base class

class Shape {

public:

void setWidth(int w) {

width = w;

void setHeight(int h) {

height = h;

protected:

int width;

int height;

};

// Derived class

class Rectangle: public Shape {

public:

int getArea() {

return (width * height);


IBIT – University of the Punjab OOP – LAB

};

int main(void) {

Rectangle Rect;

Rect.setWidth(5);

Rect.setHeight(7);

// Print the area of the object.

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

return 0;

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

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


following result –

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

Total area: 35

-----------------------------------------------------------------------------------
IBIT – University of the Punjab OOP – LAB

Access Control and Inheritance


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

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

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

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

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


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

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


class, public members of the base class become public members of the derived
class and protected members of the base class become protected members of
the derived class. A base class's private members are never accessible directly
from a derived class, but can be accessed through calls to
the public and protected members of the base class.
 Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class
become protected members of the derived class.
 Private Inheritance − When deriving from a private base
class, public and protected members of the base class become private members
of the derived class.
IBIT – University of the Punjab OOP – LAB

Multiple Inheritance

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

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

Where access is one of public, protected, or private and would be given for every base
class and they will be separated by comma as shown above. Let us try the following
example –

Program :

#include <iostream>

using namespace std;

// Base class Shape

class Shape {

public:

void setWidth(int w) {

width = w;

void setHeight(int h) {

height = h;

protected:

int width;

int height;
IBIT – University of the Punjab OOP – LAB

};

// Base class PaintCost

class PaintCost {

public:

int getCost(int area) {

return area * 70;

};

// Derived class

class Rectangle: public Shape, public PaintCost {

public:

int getArea() {

return (width * height);

};

int main(void) {

Rectangle Rect;

int area;

Rect.setWidth(5);
IBIT – University of the Punjab OOP – LAB

Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.

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

// Print the total cost of painting

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

return 0;

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

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


following result −

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

Total area: 35

Total paint cost: $2450

-----------------------------------------------------------------------------------
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Multilevel Inheritance:
Objective(s):

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

Program :

#include<iostream>

#include<cstring>

using namespace std;

//base class

class animal {

protected:

int legs;

string hair;

public:

void body(int a,string b){

legs=a;

hair=b;
IBIT – University of the Punjab OOP – LAB

};

//child class

class lion:public animal{

protected :

string color;

public:

void color1(string c){

color=c;

cout<<c<<endl;

void bodgshape(){

cout<< legs<<endl<<hair;

};
IBIT – University of the Punjab OOP – LAB

class lionspeed:public lion{

public:

void speed(){

cout<<"80 kmph";

};

int main(){

//lion l;

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

//l.color1("blue");

//l.bodgshape();

lionspeed s;

s.body(4,"Hair");

s.color1("white");
IBIT – University of the Punjab OOP – LAB

s.bodgshape();

s.speed();

Output:

white

Hair80 kmph
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

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

Here is respective Model and Code for the above example.

Program :
#include<iostream.h>

class Student;

class Department
{
char* name_p;

public:

Department(char *dName)
{
cout<<"Department::ctor\n";
name_p = new char(sizeof(strlen(dName)));
name_p = dName;
}
IBIT – University of the Punjab OOP – LAB

char* dName() const


{
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);
}
IBIT – University of the Punjab OOP – LAB

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

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

static unsigned int index;


static Course *courseList[4];

public:

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


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

if (index < 4)
{
courseName_p = new char(sizeof(strlen(crseName)));
courseName_p = crseName;
IBIT – University of the Punjab OOP – LAB

//insert this Course in courseList


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

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

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


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

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


char * getDeptName() const {return(dept_p->dName());};
IBIT – University of the Punjab OOP – LAB

char * getCourseName()const {return(courseName_p);};


};

unsigned int Course::index =0;


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

int main()
{
int i;

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


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

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


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

cout<<"\n";

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


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

cout<<"\n";

cout<<"Here class Course Associates Student and Department, with a Course name ...\
n";
Course course1("DataStructure",studentNames[0], departNames[1]);
Course course2("Maths",studentNames[3], departNames[0]);
Course course3("Geometry",studentNames[2], departNames[0]);
IBIT – University of the Punjab OOP – LAB

Course course4("CA",studentNames[1], departNames[1]);

cout<<"\n";

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


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

cout<<"\n";

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

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


{
delete studentNames[i];
}

cout<<"\n";

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


{
delete departNames[i];
}

cout<<"\n";

return(0);
}

output:
IBIT – University of the Punjab OOP – LAB

------

Example of Association class...


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

We have got 4 students ...


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

We have got 2 Departments...


Department::ctor
Department::ctor

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

Finding a Student using Course and Department...


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

Deletion of objects...

Student::dtor
Student::dtor
Student::dtor
Student::dtor
IBIT – University of the Punjab OOP – LAB

Department::dtor
Department::dtor
Course:dtor
Course:dtor
Course:dtor
Course:dtor
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

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()
{
IBIT – University of the Punjab OOP – LAB

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;
}
processor(double cspeed){
clockspeed=cspeed;
IBIT – University of the Punjab OOP – LAB

double getclockspeed(){

return clockspeed;
}
void setclockspeed(double cs){

clockspeed=cs;

}
};
class computer{

processor *processor1;

public:
void set processor (processor *processor1){

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

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

this->processor1->setclockspeed(11111);

}
void print(){
//cout<<"Operating System"<<operatingsystem;
cout<<"Clock speed "<<processor1->getclockspeed();
}
IBIT – University of the Punjab OOP – LAB

};
int main(){
processor p(5.5);
//calling parameterize contructor
{
computer c1;
c1.setprocessor(&p);
)
c1.print();
}
cout<<" Clock Speed "<<p.getclockspeed();
return 0;
}
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

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

Implementation details:

1. Typically we use normal member variables


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

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

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

Here is respective Model and Code for the above example.

Program :
#include<iostream.h>

class House;

class Room
{
public:
IBIT – University of the Punjab OOP – LAB

Room()
{
};

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


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

Room(House* hse, char* myName)


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

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

~Room()
{
cout<<"Room:dtor\n";
myHse_p = NULL;
delete (name_p);
IBIT – University of the Punjab OOP – LAB

};

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

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


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

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

class House
{
public:

House(char *myName)
{
cout<<"House::ctor\n";
name_p = new char(sizeof(strlen(myName)));;
name_p = myName;

Room::initList_v(roomsList_p);
IBIT – University of the Punjab OOP – LAB

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

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


roomsList_p[1] = myRoom;

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


roomsList_p[2] = myRoom;
}

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

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


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

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

void disp()
IBIT – University of the Punjab OOP – LAB

{
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];
};

int main()
{

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


cout<<"-----------------------------------------\n\n";
House hse("Vishranti Nilaya");
IBIT – University of the Punjab OOP – LAB

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...
Name of the House :Vishranti Nilaya

Rooms details...
Kitchen
BedRoom
Drwaing Room

Here House itself creates the Rooms and Deletes as well, before it gets deletd...
House:dtor
Delete all the Rooms ...
IBIT – University of the Punjab OOP – LAB

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;
}
void printDate(){
cout<<month <<"/" <<day <<"/" <<year <<endl;
}
private:
int month;
int day;
int year;

};

class People{

public:
IBIT – University of the Punjab OOP – LAB

People(string cname, Birthday cdateOfBirth):name(cname),


dateOfBirth(cdateOfBirth)
{

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

private:
string name;
Birthday dateOfBirth;

};
int main() {

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

}-------------------------------------------------------------------------------------------------------------
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Friend Function and Friend Classes


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

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

Program :
#include <iostream>
using namespace std;

class Box {
double width;

public:
IBIT – University of the Punjab OOP – LAB

friend void printWidth( Box box );


void setWidth( double wid );
};

// Member function definition


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

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


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

// Main function for the program


int main() {
Box box;

// set box width without member function


box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return 0;
}

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


following result −
IBIT – University of the Punjab OOP – LAB

Width of box : 10

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

// forward declaration
class B;
class A {
private:
int numA;
public:
A(): numA(12) { }
// friend function declaration
friend int add(A, B);
};
class B {
private:
int numB;
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);
}
IBIT – University of the Punjab OOP – LAB

int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}

Output
Sum: 13
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Operator Overloading (Operator and Function)


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

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

void operator++();

void disp();
};

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


a=x;
IBIT – University of the Punjab OOP – LAB

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;

class Distance {
private:
int feet; // 0 to infinite
IBIT – University of the Punjab OOP – LAB

int inches; // 0 to 12

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

// method to display distance


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

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main() {
Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation


IBIT – University of the Punjab OOP – LAB

D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

return 0;
}

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

Binary Operators Overloading in C++


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

Program :
//binary operator overloading

#include<iostream>
using namespace std;
class student{
private:
int num;
int marks;
public:
student(){
num=0;
marks=0;

}
IBIT – University of the Punjab OOP – LAB

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(){
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;
IBIT – University of the Punjab OOP – LAB

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;
}

void setLength( double len ) {


length = len;
}

void setBreadth( double bre ) {


breadth = bre;
}

void setHeight( double hei ) {


height = hei;
IBIT – University of the Punjab OOP – LAB

// Overload + operator to add two Box objects.


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

// Main function for the program


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

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

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
IBIT – University of the Punjab OOP – LAB

Box2.setHeight(10.0);

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

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

// Add two object as follows:


Box3 = Box1 + Box2;

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

return 0;
}

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


following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

Ostream, Istream Operator Overloading


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

int id;
string name;
public :

void set(int a,string b){

cin>>a>>b;
IBIT – University of the Punjab OOP – LAB

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

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

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

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

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


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

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

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


}
};
int main(){
IBIT – University of the Punjab OOP – LAB

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;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output, const Distance &D ) {
IBIT – University of the Punjab OOP – LAB

output << "F : " << D.feet << " I : " << D.inches;
return output;
}

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


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

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

return 0;
}
When the above code is compiled and executed, it produces the
following result −
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
IBIT – University of the Punjab OOP – LAB

_
IBIT – University of the Punjab OOP – LAB

__________________________________________________________________
IT260 - Object Oriented Programming Instructor:

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.

C++ Virtual Function - Properties:

C++ virtual function is,


IBIT – University of the Punjab OOP – LAB

* A member function of a class


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

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

};
class C:public A{
int c;
public:
C():A()
{
IBIT – University of the Punjab OOP – LAB

c=0;

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

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


}

};

int main()
{

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

Program :
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
IBIT – University of the Punjab OOP – LAB

public:
void set_values (int a, int b)
{ width=a;
height=b; }
virtual int area ()
{ return 0; }
};
class Rectangle: public Polygon {

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

class Triangle: public Polygon {


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

int main () {
Rectangle rect;
Triangle trgl;
Polygon poly;
Polygon * ppoly1 ;//declare the pointer
ppoly1= &rect;// store the address
Polygon * ppoly2 ;
ppoly2= &trgl;
Polygon * ppoly3 ;
IBIT – University of the Punjab OOP – LAB

ppoly3 = &poly;
ppoly1->set_values (4,5);//call the value
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';

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


return 0;
}

Task 3:
#include<iostream>
using namespace std;
class base{
public:
void disp()
{
cout<<"base class"<<endl;
}
virtual void show()
{
cout<<"Base class show:";
}
};
class derived:public base
{
void disp()
{
cout<<"derived class"<<endl;
IBIT – University of the Punjab OOP – LAB

}
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
ptr->show();
return 0;
}
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

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

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

Pure Virtual Functions


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

Program :
// CPP program to illustrate

// concept of Virtual Functions

#include<iostream>

using namespace std;

class base

public:

virtual void print ()

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

void show ()

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

};
IBIT – University of the Punjab OOP – LAB

class derived:public base

public:

void print ()

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

void show ()

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

};

int main()

base *bptr;

derived d;

bptr = &d;

//virtual function, binded at runtime

bptr->print();

// Non-virtual function, binded at compile time

bptr->show();

Program 2 :
#include<iostream>
IBIT – University of the Punjab OOP – LAB

using namespace std;

class A{

public:

virtual void disp()=0;

};

class B:public A{

private:

int val1;

public:

B(int x){

val1= x;

void disp(){

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

};

class C:public A{

private:

int val2;

public:

C(int x){

val2= x;

void disp(){

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


IBIT – University of the Punjab OOP – LAB

};

int main(){

A *basep;

B objb(100);

basep=&objb;

basep->disp();

C objc(200);

basep=&objc;

basep->disp();

return 0;

IT260 - Object Oriented Programming Instructor:


IBIT – University of the Punjab OOP – LAB

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

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

Program :Array in Function Templates


#include<iostream>

using namespace std;

template <class t>


t sum(t a[],int size){
t s=0;
for(int i=0;i<size;i++){
IBIT – University of the Punjab OOP – LAB

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

Program :Function Templates with different arguments


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

Program :

#include <iostream>
#include <string>
IBIT – University of the Punjab OOP – LAB

using namespace std;

template <typename T>


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

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

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

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

return 0;
}

Program : Function overloading in Templates


#include<iostream>
using namespace std;
template <class t>
t sum(t a,t b){
return a+b;
IBIT – University of the Punjab OOP – LAB

}
template <class t>
t sum(t a,t b,t c){

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

Class Template
Just as we can define function templates, we can also define class templates. The general
form of a generic class declaration is shown here −
template <class type> class class-name {
.
.
.
}
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>
IBIT – University of the Punjab OOP – LAB

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()
};
template <class t>
t student<t>::sum()
{

return a+b;
}
int main(){
student <int> s;
s.name(5,6);
s.display();
cout<< s.sum();
}
IBIT – University of the Punjab OOP – LAB

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

using namespace std;

template <class T>


class Stack {
private:
vector<T> elems; // elements

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

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


return elems.empty();
}
};

template <class T>


void Stack<T>::push (T const& elem) {
// append copy of passed element
IBIT – University of the Punjab OOP – LAB

elems.push_back(elem);
}

template <class T>


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

// remove last element


elems.pop_back();
}
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
IBIT – University of the Punjab OOP – LAB

// manipulate int stack


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

// manipulate string stack


stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
} catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
IBIT – University of the Punjab OOP – LAB

IT260 - Object Oriented Programming Instructor:

C++ Exception Handling


An exception is an unexpected event that occurs during program execution. For example,
Divide by zero = 7/0;
The above code causes an exception as it is not possible to divide a number by 0.
The process of handling these types of errors in C++ is known as exception handling.
In C++, we handle exceptions with the help of the try and catch blocks, along with
the throw keyword.
try - code that may raise an exception
throw - throws an exception when an error is detected
catch - code that handles the exception thrown by the throw keyword
Note: The throw statement is not compulsory, especially if we use standard C++ exceptions.

Syntax for Exception Handling in C++


The basic syntax for exception handling in C++ is given below:
try{
// code that may raise an exception
through argument;
}
catch(exception){
//code to handle exception
}
Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by the catch block.
When an exception occurs, the throw statement throws an exception, which is caught by
the catch block.
The catch block cannot be used without the try block.

Example 1: C++ Exception Handling


IBIT – University of the Punjab OOP – LAB

#include <iostream>

#include <stdexcept>

double divide(double numerator, double denominator) {

if (denominator == 0) {

throw std::invalid_argument("Division by zero");

return numerator / denominator;

int main() {

double numerator, denominator;

std::cout << "Enter numerator: ";

std::cin >> numerator;

std::cout << "Enter denominator: ";

std::cin >> denominator;

try {

double result = divide(numerator, denominator);

std::cout << "Result: " << result << std::endl;

catch (const std::invalid_argument& e) {

std::cerr << "Exception caught: " << e.what() << std::endl;

return 0;

Output 1
Enter numerator: 72

Enter denominator: 0

Error: Cannot divide by 0


IBIT – University of the Punjab OOP – LAB

Output 2
Enter numerator: 72

Enter denominator: 3

72 / 3 = 24

The above program divides two numbers and displays the result. But an exception
occurs if the denominator is 0.
To handle the exception, we have put the code divide = numerator /
denominator; inside the try block. Now, when an exception occurs, the rest of the code
inside the try block is skipped.
The catch block catches the thrown exception and executes the statements inside it.
If none of the statements in the try block generates an exception, the catch block is
skipped.

Working of
try, throw, and catch statements in C++

Notice that we have thrown the int literal 0 with the code throw 0;.
We can throw any literal or variable or class, depending on the situation and depending
on what we want to execute inside the catch block.
The catch parameter int num_exception takes the value passed by the throw statement i.e.
the literal 0.
IBIT – University of the Punjab OOP – LAB

Write a program to implement the exception handling with multiple catch statements.

#include<iostream.h> void

test(int x)
{

try
{

if(x==1)
throw x;
else
if(x==0)
throw 'x';
else
if(x==-1)
throw 1.0;
} cout<<"End of try-black\n";

catch(char c)
{

cout<<"Caught a Character\n";
}

catch(int c)
{

cout<<"Caught an Integer\n";
}

catch(double c)
{

cout<<"Caught a Double\n";
}

cout<<"End of try-catch system\n";


}

int main()
{

cout<<"Testing Multiple Catches\n"; cout<<"x==1\n";


test(1); cout<<"x==0\n";
test(0); cout<<"x==2\n";
test(2);

return 0;
}
IBIT – University of the Punjab OOP – LAB

Write a program to implement the exception handling with rethrowing in exception.

#include<iostream.h>

void divide(double x, double y)


{

cout<<"Inside Function\n"; try


{

if(y==0.0)
throw y;
else
cout<<"Division ="<<x/y<<"\n";
}

catch(double)
{

cout<<"Caught double inside function\n"; throw;


}

cout<<"End of Function\n";
}

int main()
{

cout<<"Inside Main\n"; try


{

divide(10.5,2.0);
divide(20.0,0.0);
}

catch(double)
{

cout<<"Caught double inside main\n";


}

cout<<"End of Main\n"; return 0;


}
IBIT – University of the Punjab OOP – LAB

Write a program to implement the exception handling with the functionality of


testing the throw restrictions.

#include<iostream.h>

void test(int x) throw(int, double)


{

if(x==0)
throw 'x';
else
if(x == 1)
throw x;
else
if(x == -1)
throw 1.0;
cout<<"End of Function Block\n";
}

int main()
{
try
{

cout<<"Testting Throw Restrictions\n"; cout<<"x == 0\n";


test(0); cout<<"x ==
1\n"; test(1);
cout<<"x == -1\n";
test(-1); cout<<"x ==
2\n"; test(2);

}
Lahore Garrison University Department of Software Engineering

catch(char c)
{

cout<<"Caught a Character\n";
}

catch(int m)
{

cout<<"Caught an Integer\n";
}

catch(double d)
{

cout<<"Caught a Double\n";
}

cout<<"End of Try-catch system\n";


return 0;
}

PAGE \* MERGEFORMAT 30

You might also like