[go: up one dir, main page]

0% found this document useful (0 votes)
22 views47 pages

Lab Manual-Spring2025 Updated

The document is a laboratory manual for the CS102 Object Oriented Programming course at Hazara University, detailing objectives, software requirements, and a comprehensive list of experiments and assignments. It covers fundamental OOP concepts, practical coding exercises, and specific tasks for students to complete using C++. The manual also includes installation instructions for the Dev-C++ software and sample code for various OOP principles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views47 pages

Lab Manual-Spring2025 Updated

The document is a laboratory manual for the CS102 Object Oriented Programming course at Hazara University, detailing objectives, software requirements, and a comprehensive list of experiments and assignments. It covers fundamental OOP concepts, practical coding exercises, and specific tasks for students to complete using C++. The manual also includes installation instructions for the Dev-C++ software and sample code for various OOP principles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Department Of Computer Science & IT

Hazara University Mansehra

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

Link to download Dev C++ (Embarcadero_Dev-Cpp_6.3_TDM-GCC 9.2_Setup)

https://sourceforge.net/projects/embarcadero-devcpp/

 How to install Dev C++


Once we have downloaded the Dev-C++ software. We need to follow the following
steps to install it. Below are the steps for the installation,

Step 1: Extract the Setup file from zip folder

Step 2: Run the following Setup by double clicking

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”.

Step 6: Specify the Location and click on “Install”

5
Step 7: Installing Libraries.

Step 8: Installation Completion.

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:

 Understand the evolution of programming paradigms leading to Object-Oriented


Programming (OOP).
 Learn the fundamental concepts and principles of OOP, including encapsulation,
inheritance, and polymorphism.

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.

Key OOP Principles:

1. Encapsulation: Binding data and functions together within a class.


2. Abstraction: Hiding the implementation details from the user.
3. Inheritance: Enabling new classes to derive properties from existing ones.
4. Polymorphism: Allowing objects to be treated as instances of their parent class.

Sample Code: Understanding OOP Concepts in C++


#include <iostream>
using namespace std;

// Class demonstrating Encapsulation


class Car {
private:
string brand;
int year;

public:
// Constructor
Car(string b, int y) {
brand = b;
year = y;
}

// Member function to display details

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:

 Private Attributes: name, age, and grade


 Public Methods:
o Constructor to initialize attributes.
o displayInfo() to print student details.
o updateGrade(int newGrade) to update the student's grade.

Expected Output:
Student Name: John Doe
Age: 20
Grade: A
Updated Grade: B

Submission Deadline:

9
Week 2
Class & Object
Objective:

 Understand the concepts of classes and objects in C++.


 Learn how to define a class, create objects, and access class members.

Introduction to Classes & Objects


In Object-Oriented Programming, a class is a blueprint for creating objects, and an object is
an instance of a class. A class defines attributes (data members) and behaviors (member
functions) that its objects will have.

Basic Syntax of a Class in C++:

class ClassName {
private:
// Data members (attributes)
public:
// Member functions (methods)
};

Sample Code: Defining and Using a Class in C++


#include <iostream>
using namespace std;

// Defining a class
class Student {
private:
string name;
int age;

public:
// Constructor
Student(string n, int a) {
name = n;
age = a;
}

// Member function to display student details


void displayInfo() {
cout << "Name: " << name << "\nAge: " << age << endl;

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:

 Private Attributes: brand, model, and year


 Public Methods:
o Constructor to initialize attributes.
o displayCarInfo() to print car details.

Expected Output:
Car Brand: Toyota
Model: Corolla
Year: 2023

Submission Deadline:

11
Week 3
Constructor & Destructor, Overloaded Constructors,
Default Copy Constructor
Objective:

 Understand the role of constructors and destructors in C++.


 Learn how to overload constructors.
 Explore the default copy constructor and its behavior.

Introduction
Constructors & Destructors

 Constructor: A special member function that initializes an object when it is created.


 Destructor: A special member function that is automatically called when an object is
destroyed.

Constructor Overloading

Constructor overloading allows defining multiple constructors with different parameters to


provide flexibility in object initialization.

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.

Sample Code 1: Constructor & Destructor


#include <iostream>
using namespace std;

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.

Sample Code 2: Overloaded Constructors


#include <iostream>
using namespace std;

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

Sample Code 3: Default Copy Constructor


#include <iostream>
using namespace std;

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:

Create a Person class with the following features:

 Private Attributes: name and age


 Public Methods:
o Default constructor setting name to "Unknown" and age to 0.
o Parameterized constructor to initialize name and age.
o Copy constructor to create a copy of an existing object.
o display() function to print details.

Expected Output:

Person 1: Name = Alice, Age = 25


Person 2 (Copy of Person 1): Name = Alice, Age = 25

Submission Deadline:

15
Week 4
Passing and Returning Objects
Objective:

 Learn how to pass and return objects to and from functions.

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.

Sample Code : Passing and Returning Objects


#include <iostream>
using namespace std;

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

// Function that accepts an object as a parameter


void compare(Rectangle r) {
if ((length * width) > (r.length * r.width))
cout << "Current rectangle is larger." << endl;
else
cout << "Passed rectangle is larger or equal." <<
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);

Rectangle rect3 = rect1.doubleSize();


cout << "Doubled Rectangle: ";
rect3.display();
return 0;
}

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:

 Private Attributes: accountNumber, balance


 Public Methods:
o Constructor to initialize the account number and balance.
o A method deposit(double amount) to add funds to the account.
o A method withdraw(double amount) to deduct funds, ensuring balance does
not go negative.
o A method transfer(BankAccount &receiver, double amount) to transfer
funds from one account to another.
o display() function to print account details.

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:

 Implement numeric arrays using the Stacks class.


 Implement character arrays using the String class.

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.

Character Array (String Class)

A character array (or string) is a sequence of characters stored in contiguous memory


locations. We will implement basic string operations.

Sample Code 1: Numeric Array (Stacks Class)


#include <iostream>
using namespace std;

class Stack {
private:
int arr[5];
int top;

public:
Stack() { top = -1; }

void push(int value) {


if (top == 4) {
cout << "Stack Overflow" << endl;
} else {
arr[++top] = value;
cout << "Pushed: " << value << endl;
}
}

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

Sample Code 2: Character Array (String Class)


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

class String {
private:
char str[100];

public:
String() { strcpy(str, ""); }

String(const char s[]) { strcpy(str, s); }

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:

 Understand the this pointer in C++.


 Learn how friend functions work and their use cases.

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.

Sample Code 1: Using this Pointer


#include <iostream>
using namespace std;

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

Sample Code 2: Friend Function


#include <iostream>
using namespace std;

class Sample {
private:
int data;

public:
Sample(int d) { data = d; }

// Friend function declaration


friend void displayData(Sample obj);
};

// Friend function definition


void displayData(Sample obj) {
cout << "Data: " << obj.data << endl;
}

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:

1. This Pointer Usage:


o Modify the Demo class to return an object reference using this.
o Implement function chaining using this.
2. Friend Function Implementation:
o Implement a BankAccount class where a friend function can transfer balance
between two accounts.
o Implement a Distance class where a friend function can compare two
distances.

Expected Output:
Demo Object:
Value: 10
Function chaining example: Value: 20

Bank Account Example:


Account 1 Balance: $500
Account 2 Balance: $1000
After transfer, Account 1 Balance: $300, Account 2 Balance: $1200

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:

 Understand the concept of operator overloading.


 Implement unary operator overloading (prefix and postfix ++ operator).
 Learn how to use the operator keyword.
 Implement binary operator overloading.
 Perform string concatenation using operator overloading.
 Overload the less than (<) operator.
 Overload the comparison (==) operator.

Introduction
Operator Overloading

Operator overloading allows us to redefine how operators work for user-defined data types.
Some commonly overloaded operators include:

 + (addition, string concatenation)


 - (subtraction)
 * (multiplication)
 / (division)
 ++ (increment)
 < (less than)
 == (comparison)

Unary Operator Overloading (++)

 The prefix ++ operator increments and then returns the new value.
 The postfix ++ operator returns the value before incrementing.

Binary Operator Overloading

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

// Overloading + for string concatenation


String operator+(String obj) {
String temp("");
strcpy(temp.str, str);
strcat(temp.str, obj.str);
return temp;
}

void display() { cout << "String: " << str << endl; }
};

int main() {
String s1("Hello "), s2("World");
String s3 = s1 + s2;
s3.display();
return 0;
}

Sample Code 3: Comparison < and == Operator Overloading


#include <iostream>
using namespace std;
class Distance {
private:
int meters;

public:
Distance(int m) : meters(m) {}

// Overloading < operator


bool operator<(Distance d) {
return meters < d.meters;
}

// 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:

1. Unary and Binary Operator Overloading:


o Modify the Counter class to overload the -- operator.
o Implement function chaining with ++ and --.
2. Overloading < and == Operators:
o Implement a Student class with overloaded < operator to compare marks.
o Implement a Book class with overloaded == operator to check if two books
have the same title.
3. Overloading + for Numeric and String Operations:
o Modify the BankAccount class to overload the + operator to add balances.
o Implement a Complex class with overloaded + and - operators.

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:

 Understand the concept of inheritance in C++.


 Learn different types of inheritance:
o Single Inheritance
o Multiple Inheritance
o Multilevel Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
 Implement different types of inheritance using C++.

Introduction
What is Inheritance?

Inheritance is a fundamental concept of Object-Oriented Programming (OOP) that allows a


class to derive properties and behavior from another class. The class that is inherited from
is called the Base Class, and the class that inherits is called the Derived Class.

Types of Inheritance:

1. Single Inheritance – One class inherits from another.


2. Multiple Inheritance – A class inherits from more than one base class.
3. Multilevel Inheritance – A class inherits from a derived class.
4. Hierarchical Inheritance – Multiple classes inherit from a single base class.
5. Hybrid Inheritance – A combination of more than one type of inheritance.

Sample Code 1: Single Inheritance


#include <iostream>
using namespace std;

class Parent {
public:
void display() {
cout << "This is the parent class." << endl;
}
};

class Child : public Parent {


};

29
int main() {
Child obj;
obj.display(); // Accessing Parent class function
return 0;
}

Sample Code 2: Multiple Inheritance


#include <iostream>
using namespace std;

class A {
public:
void showA() {
cout << "Class A" << endl;
}
};

class B {
public:
void showB() {
cout << "Class B" << endl;
}
};

class C : public A, public B {


};

int main() {
C obj;
obj.showA();
obj.showB();
return 0;
}

Sample Code 3: Multilevel Inheritance


#include <iostream>
using namespace std;

class Grandparent {
public:
void show() {
cout << "Grandparent class" << endl;
}
};

class Parent : public Grandparent {


};

30
class Child : public Parent {
};

int main() {
Child obj;
obj.show();
return 0;
}

Sample Code 4: Hierarchical Inheritance


#include <iostream>
using namespace std;

class Parent {
public:
void show() {
cout << "Parent class function" << endl;
}
};

class Child1 : public Parent {


};

class Child2 : public Parent {


};

int main() {
Child1 obj1;
Child2 obj2;
obj1.show();
obj2.show();
return 0;
}

Sample Code 5: Hybrid Inheritance


#include <iostream>
using namespace std;

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

class D : public B, public C {


};

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:

1. Implement a Multilevel Inheritance Example:


o Create a Person class with basic details.
o Create a Student class inheriting from Person.
o Create a GraduateStudent class inheriting from Student.
2. Implement Multiple Inheritance:
o Create a Employee class.
o Create a Manager class.
o Create a Director class inheriting from both Employee and Manager.
3. Implement a Hybrid Inheritance:
o Create a Teacher class and Researcher class.
o Create a Professor class that inherits from both.

Expected Output:
Person Info:
Name: John
Age: 30

Student Info:
School: ABC University

Graduate Student Info:


Degree: Masters

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:

 Understand the concept of Association, Aggregation, and Composition in C++.


 Differentiate between Association, Aggregation, and Composition.
 Implement real-world examples of each concept in C++.

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 (Weak Relationship)

Aggregation is a special type of association where one class owns another class but the
owned object can exist independently.

Composition (Strong Relationship)

Composition is a type of aggregation where the contained object cannot exist without the
container object.

Sample Code 1: Association Example


#include <iostream>
using namespace std;

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

Sample Code 2: Aggregation Example


#include <iostream>
using namespace std;

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

Sample Code 3: Composition Example


#include <iostream>
using namespace std;

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:

 Understand the concept of Polymorphism in C++.


 Differentiate between Compile-time and Run-time Polymorphism.
 Implement Virtual Functions and Pure Virtual Functions.
 Understand the role of abstract classes in C++.

Introduction
Polymorphism

Polymorphism allows one interface to be used for different types. It is mainly of two types:

1. Compile-time Polymorphism (Function Overloading & Operator Overloading)


2. Run-time Polymorphism (Virtual Functions & Dynamic Binding)

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.

Pure Virtual Functions & Abstract Classes

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.

Sample Code 1: Virtual Function Example


#include <iostream>
using namespace std;

class Base {
public:
virtual void show() { // Virtual Function
cout << "Base class show() function" << endl;
}
};

class Derived : public Base {

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

Sample Code 2: Pure Virtual Function & Abstract Class


#include <iostream>
using namespace std;

class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {


public:
void draw() override {
cout << "Drawing a Circle" << endl;
}
};

class Rectangle : public Shape {


public:
void draw() override {
cout << "Drawing a Rectangle" << endl;
}
};

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:

1. Virtual Function Example:


o Implement a Media class with a virtual play() function.
o Derive Audio and Video classes, overriding play().
2. Abstract Class Example:
o Implement an Employee class with a pure virtual function
calculateSalary().
o Derive FullTimeEmployee and PartTimeEmployee classes that implement
calculateSalary().
3. Real-world Polymorphism Implementation:
o Implement a BankAccount class with a virtual function
calculateInterest().
o Derive SavingsAccount and CurrentAccount classes that override
calculateInterest().

Expected Output:

Playing audio...
Playing video...

Employee Salaries:
Full-time Employee: $5000
Part-time Employee: $2000

Bank Account Interest:


Savings Account Interest: 5%
Current Account Interest: 2%

Submission Deadline:

40
Week 11
I/O Processing in C++
Objective:

 Understand Input/Output (I/O) processing in C++.


 Learn about the iostream library and its classes.
 Explore file handling concepts and modes of file operations.
 Implement reading from and writing to files.

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:

 istream → Input Stream (used with cin)


 ostream → Output Stream (used with cout)
 fstream → File Stream (for file handling)
 ifstream → Input File Stream (reading files)
 ofstream → Output File Stream (writing files)

File Handling in C++

Files in C++ are handled using fstream, ifstream, and ofstream. Files can be opened in
various modes such as:

Mode Description

ios::in Open file for reading

ios::out Open file for writing

ios::app Append data to file

ios::trunc Truncate file contents

ios::binary Open file in binary mode

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

Sample Code 2: Reading from a File


#include <iostream>
#include <fstream>
using namespace std;

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:

1. File Operations in C++:


o Implement a program that writes multiple lines to a file.
o Read the contents of the file and display them.
o Append additional content to the file and verify.
2. Student Database System:
o Create a program that stores student data in a file.
o Implement functions to add, update, delete, and search records.
3. File Encryption and Decryption:
o Implement a simple encryption algorithm that encrypts text before saving to a
file.
o Implement a decryption function to retrieve the original text.

43
Expected Output:

Enter student name: John Doe


Enter roll number: 1234
Enter marks: 85
Student data saved successfully!

Reading file contents:


Name: John Doe
Roll No: 1234
Marks: 85

Submission Deadline:

44
Week 12
Exception Handling in C++
Objective:

 Understand the concept of exception handling in C++.


 Learn how to use try, catch, and throw statements.
 Implement exception handling for different scenarios.

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:

 try block: Contains code that may throw an exception.


 throw statement: Used to throw an exception when an error occurs.
 catch block: Handles the exception thrown by the throw statement.

Syntax:

try {
// Code that may cause an exception
throw exceptionType;
} catch (exceptionType variable) {
// Code to handle exception
}

Sample Code 1: Handling Division by Zero


#include <iostream>
using namespace std;

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

Sample Code 2: Handling Array Index Out of Bounds


#include <iostream>
using namespace std;

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

Sample Code 3: Exception Handling with Multiple Catch


Blocks
#include <iostream>
using namespace std;

void checkValue(int value) {


try {
if (value < 0)
throw "Negative value error";
if (value == 0)
throw 0;
cout << "Valid value: " << value << endl;
} catch (const char* msg) {
cout << "Exception: " << msg << endl;
} catch (int i) {
cout << "Exception: Value cannot be zero" << endl;
}
}

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:

1. User Input Validation:


o Implement a program that takes an integer input from the user and throws an
exception if:
 The input is negative.
 The input is too large.
o Use multiple catch blocks to handle different types of errors.
2. File Handling with Exception Handling:
o Create a program that attempts to open a file and throws an exception if the
file does not exist.
o Catch the exception and display an error message.
3. Student Grade Validation:
o Implement a system where a student’s grade is entered (between 0 and 100).
o If an invalid grade is entered, throw an exception and handle it appropriately.

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

You might also like