Lab Manual-Spring2025 Updated
Lab Manual-Spring2025 Updated
Laboratory Manual
(CS102 Object Oriented Programing)
Spring Semester 2025
Course Instructor
Ghulam Mustafa Assad
1
Objectives:
Gain a solid understanding of key OOP concepts such as classes, objects, inheritance,
polymorphism, encapsulation, and abstraction.
Apply theoretical knowledge to practical problems, reinforcing learning through
hands-on experience.
Develop problem-solving skills by designing and implementing solutions using OOP
principles.
Improve debugging and testing skills by identifying and fixing errors in code and
ensuring that the implemented solutions work as expected.
Gain experience in developing small to medium-sized projects, integrating various
OOP concepts, and possibly working with external libraries and APIs.
2
Software : Dev-C++ will be used to implement the programs of Object Oriented
Programming Course
https://sourceforge.net/projects/embarcadero-devcpp/
3
Step 3: Select the language English by clicking “OK”.
Step 4: Now, accept the License Terms & Agreement by clicking “I Agree”.
4
Step 5: Choosing Components To Be Installed. And click on “Next”.
5
Step 7: Installing Libraries.
6
List of Experiments
1. Lab 1: Evolution of OOP
o Introduction to Object-Oriented Programming
o Principles of OOP
o Benefits and Comparison with Procedural Programming
2. Lab 2: Classes and Objects
o Defining and Using Classes in C++
o Creating Objects and Accessing Members
o Sample Programs and Exercises
3. Lab 3: Constructors and Destructors
o Role of Constructors and Destructors
o Overloading Constructors
o Default Copy Constructors
4. Lab 4: Passing and Returning Objects
o Object as Function Arguments
o Returning Objects from Functions
o Implementing Programs Using Objects in Functions
5. Lab 5: Arrays of Objects (Stack and String Class)
o Numeric Array Implementation (Stack Class)
o Character Array Implementation (String Class)
6. Lab 6: this Pointer and Friend Functions
o Understanding the this Pointer
o Implementing Friend Functions in C++
7. Lab 7: Operator Overloading
o Unary and Binary Operator Overloading
o Overloading ++ (prefix & postfix)
o String Concatenation and Comparison Overloading
8. Lab 8: Inheritance and Types of Inheritance
o Single, Multiple, Multilevel, Hierarchical, and Hybrid Inheritance
o Code Implementation of Different Inheritance Types
9. Lab 9: Association, Aggregation, and Composition
o Understanding Relationships Between Classes
o Implementation and Practical Examples
10. Lab 10: Polymorphism
o Function Overriding and Virtual Functions
o Pure Virtual Functions and Abstract Classes
11. Lab 11: I/O Processing in C++
o Introduction to File Handling
o File Read/Write Operations and File Modes
12. Lab 12: Exception Handling
o Handling Errors Using try, catch, and throw
o Implementing Exception Handling in Real-World Scenarios
7
Week 1
Evolution of OOP & Concepts and Principles of OOP
Objective:
Introduction to OOP
Object-Oriented Programming (OOP) is a paradigm that organizes software design around
objects rather than functions and logic. It was developed to overcome the limitations of
procedural programming, such as code redundancy and poor maintainability.
public:
// Constructor
Car(string b, int y) {
brand = b;
year = y;
}
8
void display() {
cout << "Brand: " << brand << ", Year: " << year <<
endl;
}
};
int main() {
Car car1("Toyota", 2022);
car1.display(); // Demonstrating encapsulation
return 0;
}
Exercise Questions
1. Define Object-Oriented Programming in your own words.
2. Explain the difference between procedural and object-oriented programming.
3. What are the four pillars of OOP? Provide a brief explanation of each.
4. Modify the given code to add a new function setYear(int y) that updates the car's
year.
Assignment
Task:
Create a C++ program that defines a Student class with the following attributes and
methods:
Expected Output:
Student Name: John Doe
Age: 20
Grade: A
Updated Grade: B
Submission Deadline:
9
Week 2
Class & Object
Objective:
class ClassName {
private:
// Data members (attributes)
public:
// Member functions (methods)
};
// Defining a class
class Student {
private:
string name;
int age;
public:
// Constructor
Student(string n, int a) {
name = n;
age = a;
}
10
}
};
int main() {
// Creating an object of Student class
Student student1("Alice", 20);
student1.displayInfo(); // Accessing class method
return 0;
}
Exercise Questions
1. What is a class? How does it differ from an object?
2. Explain the significance of access specifiers (private, public) in a class.
3. Modify the given code to add a new attribute grade and display it in the
displayInfo() function.
4. How is a constructor different from a regular member function?
Assignment
Task:
Create a C++ program that defines a Car class with the following attributes and methods:
Expected Output:
Car Brand: Toyota
Model: Corolla
Year: 2023
Submission Deadline:
11
Week 3
Constructor & Destructor, Overloaded Constructors,
Default Copy Constructor
Objective:
Introduction
Constructors & Destructors
Constructor Overloading
Copy Constructor
A copy constructor is used to create a new object as a copy of an existing object. C++
provides a default copy constructor, but we can also define a custom one.
class Student {
private:
string name;
int age;
public:
// Constructor
Student(string n, int a) {
name = n;
12
age = a;
cout << "Constructor called for " << name << endl;
}
// Destructor
~Student() {
cout << "Destructor called for " << name << endl;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Student s1("Alice", 20);
s1.display();
return 0;
} // Destructor will be called automatically when the object
goes out of scope.
class Car {
private:
string brand;
int year;
public:
// Default Constructor
Car() {
brand = "Unknown";
year = 0;
}
// Parameterized Constructor
Car(string b, int y) {
brand = b;
year = y;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year <<
endl;
}
};
13
int main() {
Car car1; // Calls default constructor
Car car2("Toyota", 2023); // Calls parameterized
constructor
car1.display();
car2.display();
return 0;
}
class Book {
public:
string title;
int pages;
// Constructor
Book(string t, int p) {
title = t;
pages = p;
}
void display() {
cout << "Title: " << title << ", Pages: " << pages <<
endl;
}
};
int main() {
Book book1("C++ Programming", 500);
Book book2 = book1; // Default copy constructor is called
book1.display();
book2.display();
return 0;
}
14
Exercise Questions
1. What is the purpose of a constructor and a destructor in a class?
2. How does constructor overloading work? Provide an example.
3. Modify the overloaded constructor example to include a third constructor that
initializes only the brand.
4. What is a copy constructor? When is it called automatically?
Assignment
Task:
Expected Output:
Submission Deadline:
15
Week 4
Passing and Returning Objects
Objective:
Introduction
Objects can be passed to functions as arguments and can also be returned from functions.
This helps in modular programming and better data manipulation.
class Rectangle {
private:
int length, width;
public:
// Constructor
Rectangle(int l, int w) {
length = l;
width = w;
}
void display() {
cout << "Length: " << length << ", Width: " << width
<< endl;
}
16
// Function that returns an object
Rectangle doubleSize() {
return Rectangle(length * 2, width * 2);
}
};
int main() {
Rectangle rect1(10, 5), rect2(7, 6);
rect1.display();
rect2.display();
rect1.compare(rect2);
Exercise Questions
1. Modify the Rectangle class to include a function add(Rectangle r) that returns a
new Rectangle whose dimensions are the sum of the two rectangles.
Assignment
Task: Create a BankAccount class with the following features:
Expected Output:
Account 1: 1001, Balance: $5000
Account 2: 1002, Balance: $3000
Transferring $1000 from Account 1 to Account 2...
Updated Balances:
Account 1: 1001, Balance: $4000
Account 2: 1002, Balance: $4000
Submission Deadline:
17
Week 5
Numeric Array (Stacks Class), Character Array (String
Class)
Objective:
Introduction
Numeric Array (Stacks Class)
A stack is a data structure that follows the Last In, First Out (LIFO) principle. We will
implement a stack using an array.
class Stack {
private:
int arr[5];
int top;
public:
Stack() { top = -1; }
18
void pop() {
if (top == -1) {
cout << "Stack Underflow" << endl;
} else {
cout << "Popped: " << arr[top--] << endl;
}
}
void display() {
if (top == -1) {
cout << "Stack is empty" << endl;
} else {
cout << "Stack elements: ";
for (int i = 0; i <= top; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
}
};
int main() {
Stack s;
s.push(10);
s.push(20);
s.push(30);
s.display();
s.pop();
s.display();
return 0;
}
class String {
private:
char str[100];
public:
String() { strcpy(str, ""); }
void display() { cout << "String: " << str << endl; }
19
void concatenate(String s2) {
strcat(str, s2.str);
}
};
int main() {
String s1("Hello");
String s2(" World!");
s1.display();
s2.display();
s1.concatenate(s2);
cout << "After Concatenation: ";
s1.display();
return 0;
}
Exercise Questions
1. Implement a stack that can store floating-point numbers instead of integers.
2. Modify the String class to support finding the length of a string.
Assignment
Task:
1. Numeric Array (Stack Class Modification): Modify the Stack class to support
dynamic memory allocation instead of a fixed-size array.
2. Character Array (String Class Enhancement):
o Add a method to compare two strings.
o Add a method to convert all characters in the string to uppercase.
Expected Output:
Stack operations:
Pushed: 10
Pushed: 20
Stack elements: 10 20
Popped: 20
Stack elements: 10
String operations:
String 1: Hello
String 2: World!
Concatenated String: Hello World!
Uppercase String: HELLO WORLD!
Comparison Result: Strings are not equal.
Submission Deadline:
20
Week 6
This Pointer, Friend Function
Objective:
Introduction
This Pointer
The this pointer is an implicit pointer available in all non-static member functions of a
class.
It holds the address of the calling object.
It is useful in handling name conflicts and returning the object itself for function
chaining.
Friend Function
A friend function is not a member of a class but has access to its private and
protected members.
It is useful in cases where an external function needs to operate on private data.
class Demo {
private:
int value;
public:
Demo(int value) {
this->value = value; // Using 'this' to differentiate
}
void display() {
cout << "Value: " << this->value << endl;
}
};
21
int main() {
Demo d(10);
d.display();
return 0;
}
class Sample {
private:
int data;
public:
Sample(int d) { data = d; }
int main() {
Sample s(50);
displayData(s);
return 0;
}
Exercise Questions
1. What is the purpose of the this pointer in C++?
2. Modify the Demo class to include a member function that returns the calling object
using this.
3. What is a friend function? When should it be used?
4. Modify the Sample class to include a friend function that modifies private data instead
of just displaying it.
5. Implement a class Rectangle where a friend function calculates the area using private
variables.
22
Assignment
Task:
Expected Output:
Demo Object:
Value: 10
Function chaining example: Value: 20
Distance Comparison:
Distance 1: 5.4 meters
Distance 2: 6.2 meters
Result: Distance 2 is greater.
Submission Deadline:
23
Week 7
Operator Overloading
Objective:
Introduction
Operator Overloading
Operator overloading allows us to redefine how operators work for user-defined data types.
Some commonly overloaded operators include:
The prefix ++ operator increments and then returns the new value.
The postfix ++ operator returns the value before incrementing.
Overloading binary operators like +, -, and < allows custom behavior for these
operations.
24
Sample Code 1: Unary ++ Operator Overloading
#include <iostream>
using namespace std;
class Counter {
private:
int value;
public:
Counter(int v) : value(v) {}
// Overloading prefix ++
Counter operator++() {
++value;
return *this;
}
// Overloading postfix ++
Counter operator++(int) {
Counter temp = *this;
value++;
return temp;
}
void display() { cout << "Value: " << value << endl; }
};
int main() {
Counter c(5);
++c;
c.display();
c++;
c.display();
return 0;
}
25
Sample Code 2: String Concatenation (+ Operator
Overloading)
#include <iostream>
#include <string.h>
using namespace std;
class String {
private:
char str[100];
public:
String(const char* s) { strcpy(str, s); }
void display() { cout << "String: " << str << endl; }
};
int main() {
String s1("Hello "), s2("World");
String s3 = s1 + s2;
s3.display();
return 0;
}
public:
Distance(int m) : meters(m) {}
// Overloading == operator
26
bool operator==(Distance d) {
return meters == d.meters;
}
};
int main() {
Distance d1(5), d2(10);
if (d1 < d2)
cout << "d1 is less than d2" << endl;
if (d1 == d2)
cout << "d1 is equal to d2" << endl;
else
cout << "d1 is not equal to d2" << endl;
return 0;
}
Exercise Questions
1. What is operator overloading, and why is it used?
2. Implement a BankAccount class where the + operator adds the balance of two
accounts.
3. Modify the Counter class to overload the -- operator.
4. Implement a Complex number class with overloaded + and - operators.
5. Implement an overloaded < operator for a Student class to compare marks.
6. Implement an overloaded == operator for a Book class to check if two books have the
same title.
Assignment
Task:
27
Expected Output:
Counter Example:
Value: 5
Value after increment: 6
Value after decrement: 5
Student Comparison:
Student 1 marks: 85
Student 2 marks: 90
Student 1 has fewer marks than Student 2
String Concatenation:
Hello World
Submission Deadline:
28
Week 8
Inheritance and Types of Inheritance
Objective:
Introduction
What is Inheritance?
Types of Inheritance:
class Parent {
public:
void display() {
cout << "This is the parent class." << endl;
}
};
29
int main() {
Child obj;
obj.display(); // Accessing Parent class function
return 0;
}
class A {
public:
void showA() {
cout << "Class A" << endl;
}
};
class B {
public:
void showB() {
cout << "Class B" << endl;
}
};
int main() {
C obj;
obj.showA();
obj.showB();
return 0;
}
class Grandparent {
public:
void show() {
cout << "Grandparent class" << endl;
}
};
30
class Child : public Parent {
};
int main() {
Child obj;
obj.show();
return 0;
}
class Parent {
public:
void show() {
cout << "Parent class function" << endl;
}
};
int main() {
Child1 obj1;
Child2 obj2;
obj1.show();
obj2.show();
return 0;
}
class A {
public:
void showA() {
cout << "Class A" << endl;
}
};
class B : public A {
public:
31
void showB() {
cout << "Class B" << endl;
}
};
class C {
public:
void showC() {
cout << "Class C" << endl;
}
};
int main() {
D obj;
obj.showA();
obj.showB();
obj.showC();
return 0;
}
Exercise Questions
1. What is inheritance in C++? Explain its advantages.
2. Implement a Vehicle class with a Car class inheriting from it.
3. Modify the Multilevel Inheritance example by adding a method in the Parent class.
4. Implement a Multiple Inheritance example where a Student inherits from both Person
and School classes.
5. Create a Hierarchical Inheritance structure where Bird and Mammal inherit from Animal.
6. Implement a Hybrid Inheritance where a TeachingAssistant class inherits from both
Student and Teacher.
32
Assignment
Task:
Expected Output:
Person Info:
Name: John
Age: 30
Student Info:
School: ABC University
Manager Info:
Managing 5 employees.
Director Info:
Directing 3 departments.
Professor Info:
Teaching 3 courses.
Researching in AI.
Submission Deadline:
33
Week 9
Association, Aggregation, and Composition
Objective:
Introduction
Association
Association is a relationship between two classes where objects of one class use objects of
another class. This relationship can be one-to-one, one-to-many, or many-to-many.
Aggregation is a special type of association where one class owns another class but the
owned object can exist independently.
Composition is a type of aggregation where the contained object cannot exist without the
container object.
class Car {
public:
void showCar() {
cout << "This is a car." << endl;
}
};
class Driver {
public:
void drive(Car &c) { // Association: Driver uses Car
cout << "Driver is driving the car." << endl;
c.showCar();
34
}
};
int main() {
Car myCar;
Driver myDriver;
myDriver.drive(myCar);
return 0;
}
class Engine {
public:
void start() {
cout << "Engine is starting..." << endl;
}
};
class Car {
private:
Engine *engine; // Aggregation: Car has an Engine
public:
Car(Engine *e) : engine(e) {}
void startCar() {
cout << "Car is starting." << endl;
engine->start();
}
};
int main() {
Engine myEngine;
Car myCar(&myEngine); // Engine exists outside Car
myCar.startCar();
return 0;
}
class Engine {
public:
Engine() { cout << "Engine created." << endl; }
~Engine() { cout << "Engine destroyed." << endl; }
void start() { cout << "Engine is running..." << endl; }
35
};
class Car {
private:
Engine engine; // Composition: Engine is part of Car
public:
Car() { cout << "Car created." << endl; }
~Car() { cout << "Car destroyed." << endl; }
void startCar() {
cout << "Car is starting." << endl;
engine.start();
}
};
int main() {
Car myCar;
myCar.startCar();
return 0;
}
Exercise Questions
1. Define Association, Aggregation, and Composition and explain the key differences.
2. Implement an Association example where a Teacher teaches multiple Students.
3. Implement an Aggregation example where a Library has a Book.
4. Implement a Composition example where a House has Rooms that cannot exist
without the House.
5. Modify the Composition Example to add a Wheel class that is part of the Car.
6. Implement a Real-World Example using a combination of Association, Aggregation,
and Composition.
36
Assignment
Task:
1. Association Example:
o Implement a Doctor and Patient class where a doctor treats multiple
patients.
2. Aggregation Example:
o Implement a University class containing multiple Departments, but the
Departments can exist independently.
3. Composition Example:
o Implement a Computer class containing a CPU and RAM, which cannot exist
without the Computer.
Expected Output:
Doctor-Patient Relationship:
Doctor treats Patient 1
Doctor treats Patient 2
University-Department Relationship:
University has Department of CS
University has Department of Math
Computer System:
CPU initialized.
RAM initialized.
Computer assembled.
Submission Deadline:
37
Week 10
Polymorphism
Objective:
Introduction
Polymorphism
Polymorphism allows one interface to be used for different types. It is mainly of two types:
Virtual Functions
A virtual function is a member function in the base class that can be overridden in a derived
class. It enables dynamic dispatch at runtime.
A pure virtual function is a function that must be implemented in derived classes. A class
containing at least one pure virtual function is called an abstract class and cannot be
instantiated.
class Base {
public:
virtual void show() { // Virtual Function
cout << "Base class show() function" << endl;
}
};
38
public:
void show() override { // Overriding base class function
cout << "Derived class show() function" << endl;
}
};
int main() {
Base *bPtr; // Pointer to base class
Derived dObj;
bPtr = &dObj;
bPtr->show(); // Calls Derived class function due to
dynamic binding
return 0;
}
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
int main() {
Shape *s1 = new Circle();
Shape *s2 = new Rectangle();
s1->draw();
s2->draw();
delete s1;
delete s2;
return 0;
}
39
Exercise Questions
1. Explain Polymorphism and its types in C++.
2. What is a virtual function, and how does it enable run-time polymorphism?
3. Implement a Vehicle class with a virtual startEngine() method and derive Car and
Bike classes that override it.
4. Implement an abstract class Animal with a pure virtual function makeSound().
Derive Dog and Cat classes from it.
5. Modify the Circle and Rectangle example to include a Triangle class.
6. Implement a real-world example using a combination of Virtual Functions and Pure
Virtual Functions.
Assignment
Task:
Expected Output:
Playing audio...
Playing video...
Employee Salaries:
Full-time Employee: $5000
Part-time Employee: $2000
Submission Deadline:
40
Week 11
I/O Processing in C++
Objective:
Introduction
I/O Streams in C++
C++ provides stream-based I/O using the iostream library. The primary classes used for I/O
operations are:
Files in C++ are handled using fstream, ifstream, and ofstream. Files can be opened in
various modes such as:
Mode Description
41
Sample Code 1: Writing to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt"); // Open file in write mode
if (!file) {
cout << "Error opening file!" << endl;
return 1;
}
file << "Hello, this is a file writing example in C++!";
file.close();
cout << "Data written to file successfully." << endl;
return 0;
}
int main() {
ifstream file("example.txt"); // Open file in read mode
if (!file) {
cout << "Error opening file!" << endl;
return 1;
}
string line;
while (getline(file, line)) { // Read file line by line
cout << line << endl;
}
file.close();
return 0;
}
42
Sample Code 3: Append Data to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt", ios::app); // Open file in
append mode
if (!file) {
cout << "Error opening file!" << endl;
return 1;
}
file << "\nAppending new line to the file.";
file.close();
cout << "Data appended successfully." << endl;
return 0;
}
Exercise Questions
1. Explain different file modes in C++.
2. Modify the file writing program to take user input and store it in a file.
3. Implement a Student Record System where student data (name, roll number, marks)
is written to a file and later read from it.
4. Modify the file reading program to count the number of words in a file.
5. Implement a program that copies content from one file to another.
Assignment
Task:
43
Expected Output:
Submission Deadline:
44
Week 12
Exception Handling in C++
Objective:
Introduction
What is Exception Handling?
Exception handling is a mechanism that allows a program to handle runtime errors gracefully,
preventing the program from crashing unexpectedly.
Key Components:
Syntax:
try {
// Code that may cause an exception
throw exceptionType;
} catch (exceptionType variable) {
// Code to handle exception
}
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
try {
if (b == 0)
throw "Division by zero is not allowed!";
cout << "Result: " << a / b << endl;
45
} catch (const char* msg) {
cout << "Exception: " << msg << endl;
}
return 0;
}
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int index;
cout << "Enter index (0-4): ";
cin >> index;
try {
if (index < 0 || index >= 5)
throw index;
cout << "Value at index " << index << " is: " <<
arr[index] << endl;
} catch (int i) {
cout << "Exception: Index " << i << " is out of
bounds!" << endl;
}
return 0;
}
int main() {
46
int num;
cout << "Enter a number: ";
cin >> num;
checkValue(num);
return 0;
}
Exercise Questions
1. Explain the difference between compile-time errors, runtime errors, and
exceptions.
2. Modify Sample Code 1 to handle multiple exceptions (e.g., negative divisor).
3. Implement an exception handling mechanism for a banking system where
withdrawal should not exceed account balance.
4. Write a program that handles string length exceptions (e.g., throwing an error if the
string is too short or too long).
5. Create a function that handles exceptions for invalid age input (e.g., age cannot be
negative or greater than 150).
Assignment
Task:
Expected Output:
Enter a number: -5
Exception: Negative value error
Enter a number: 0
Exception: Value cannot be zero
Enter a number: 10
Valid value: 10
Submission Deadline:
47