0% found this document useful (0 votes)
13 views43 pages

Oop Notes of Final

Inheritance in C++ is a key feature of Object-Oriented Programming that allows a derived class to acquire properties and behaviors from a base class, promoting code reusability and extensibility. It includes various types such as single, multilevel, hierarchical, multiple, and hybrid inheritance, each with specific use cases and syntax. Additionally, the document covers concepts like access specifiers, method overriding, and the importance of inheritance in modeling real-world relationships.

Uploaded by

khadijaashraf585
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views43 pages

Oop Notes of Final

Inheritance in C++ is a key feature of Object-Oriented Programming that allows a derived class to acquire properties and behaviors from a base class, promoting code reusability and extensibility. It includes various types such as single, multilevel, hierarchical, multiple, and hybrid inheritance, each with specific use cases and syntax. Additionally, the document covers concepts like access specifiers, method overriding, and the importance of inheritance in modeling real-world relationships.

Uploaded by

khadijaashraf585
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

📘 5.

Inheritance in C++ (Object-Oriented


Programming)

🔹 5.1 Definition of Inheritance


Inheritance is a feature in Object-Oriented Programming (OOP) that allows a class
(called the derived class) to acquire properties and behaviors (data members and
member functions) from another class (called the base class).

Simple Words: It helps you reuse code and avoid writing the same code again.

🔹 5.2 Importance of Inheritance


 ✅ Code Reusability: Write common code once in the base class, use it in
multiple derived classes.
 ✅ Extensibility: You can add new features without modifying existing
code.
 ✅ Improves Code Structure: Keeps code clean, organized, and easy to
understand.
 ✅ Real-world Modeling: Helps represent real-world relationships like
“Student is a Person”.

🔹 5.3 Syntax of Inheritance

class Base {
// base class members
};

class Derived : access_modifier Base {


// derived class members
};

Note: Access modifiers can be public, protected, or private.


🔹 Access Specifiers and Diagrams
📌 Access Specifiers:
Access Accessible in Base Accessible in Derived Class (Public Accessible Outside
Specifier Class Inheritance) Class

public ✅ Yes ✅ Yes ✅ Yes

protected ✅ Yes ✅ Yes ❌ No

private ✅ Yes ❌ No ❌ No

🔹 5.5 Functions of Inheritance (Uses)


1. Avoid code duplication.
2. Help in making hierarchical classification (Person → Student).
3. Enables polymorphism using virtual functions.
4. Helps in better data management.
5. Supports modular and scalable programming.

🔹 5.6 Types of Inheritance (with Explanation and


Code)

🔸 1. Single Inheritance

Definition: One base class, one derived class.

class Animal {
public:
void sound() {
cout << "Animal makes sound" << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Dog barks" << endl;
}
};

✅ Explanation: Dog inherits from Animal. It can use both sound() and bark().

🔸 2. Multilevel Inheritance

Definition: Class inherits from a derived class which is also derived from another
class.
class A {
public:
void showA() {
cout << "Class A" << endl;
}
};

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

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

✅ Explanation: C can access showA() and showB() because it indirectly inherits A.

🔸 3. Hierarchical Inheritance

Definition: Multiple classes inherit from a single base class.


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

class Child1 : public Parent {


public:
void show1() {
cout << "Child 1" << endl;
}
};

class Child2 : public Parent {


public:
void show2() {
cout << "Child 2" << endl;
}
};

✅ Explanation: Both Child1 and Child2 use show() from Parent.

🔸 4. Multiple Inheritance

Definition: One class inherits from more than one base class.
class A {
public:
void funA() {
cout << "Class A" << endl;
}
};

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

class C : public A, public B {


public:
void funC() {
cout << "Class C" << endl;
}
};

✅ Explanation: C can use functions from both A and B.


🔸 5. Hybrid Inheritance

Definition: Combination of more than one type of inheritance.


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

class B : public A {};


class C : public A {};
class D : public B, public C {};

❌ Problem: D gets two copies of A, causing ambiguity.


✅ Solution: Use Virtual Inheritance.

🔸 6. Virtual Inheritance (Solving Diamond Problem)


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

class B : virtual public A {};


class C : virtual public A {};
class D : public B, public C {};

int main() {
D obj;
obj.showA(); // ✅ No ambiguity
}

✅ Explanation: virtual ensures only one copy of A is inherited.

🔹 5.7 UML Diagram for Inheritance


+--------------+
| Vehicle |
+--------------+
| - speed |
| +move() |
+--------------+
/ \
/ \
+-------------+ +-------------+
| Car | | Bike |
+-------------+ +-------------+
| - fuelType | | - hasGears |
+-------------+ +-------------+

🔹 5.8 Real Life Examples


Base Class Derived Class
Person Student, Teacher
Shape Circle, Rectangle
Animal Dog, Cat
Vehicle Car, Bike

🔹 5.9 Extra Tips


1. Always use public inheritance unless there's a specific need.
2. Use virtual for polymorphism with inheritance.
3. Use virtual inheritance in complex hybrid systems to avoid ambiguity.
4. Avoid deep inheritance (e.g., more than 3 levels) to keep things simple.
5. Prefer composition over inheritance when “has-a” relationship fits better.

🔹 5.10 Problem Analysis of Inheritance


✅ What is Problem Analysis in Inheritance?

Problem analysis means understanding how inheritance can solve real-world


problems in software development by modeling relationships and reducing
redundancy.
🔸 💡 Why Do We Use Inheritance in Problem Solving?

 To model real-world "is-a" relationships (e.g., Student is a Person).


 To reuse code written in base classes.
 To make the system scalable and maintainable.
 To support future extension without changing existing code.
 To avoid code duplication when multiple classes share common features.

🔸 🧠 Example Problem (Before Inheritance)

Suppose we have two classes: Teacher and Student. Both have name, age, and
display() function.

❌ You would need to write the same code twice in both classes.

🔸 ✅ Solution Using Inheritance

We create a base class Person and put common data/functions in it. Then, Student
and Teacher inherit from Person.
#include <iostream>
using namespace std;

class Person {
protected:
string name;
int age;
public:
void getDetails() {
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

class Student : public Person {


public:
void study() {
cout << name << " is studying." << endl;
}
};

class Teacher : public Person {


public:
void teach() {
cout << name << " is teaching." << endl;
}
};

int main() {
Student s;
Teacher t;

cout << "Enter Student Info:" << endl;


s.getDetails();
s.display();
s.study();

cout << "\nEnter Teacher Info:" << endl;


t.getDetails();
t.display();
t.teach();

return 0;
}

🔍 ✅ Explanation:

 Person contains common features (name, age, display()).


 Student and Teacher inherit these features.
 No code duplication.
 If you need to update name or age logic, just change it in one place (base
class).

📈 Real-World Problem Solving With Inheritance:

Real Problem Solution With Inheritance


Different user types (Admin, Student, Staff) Create base class User, inherit for
need login, name, email each user type
Vehicles have common properties but Base class Vehicle, derived Car,
Real Problem Solution With Inheritance
different behaviors Bike, Bus
Base class Employee, derived
Employees of different departments
Manager, Clerk, Engineer

📝 Summary:

 Inheritance is a key tool in solving large, complex software problems.


 Helps in designing modular, clean, reusable code.
 Reduces errors and improves consistency.
 Essential in real-world applications like management systems, inventory,
education portals, etc.

📘 6. Types of Inheritance (with Method


Overriding and UML)

🔹 6.1 Introduction
Inheritance allows one class to inherit the members of another class. It supports
code reusability and helps model real-world relationships. C++ supports several
types of inheritance.

🔹 6.2 Enhanced Version of Stack Example using


Inheritance
Goal: Use inheritance to enhance the functionality of a basic stack.
cpp
CopyEdit
#include <iostream>
using namespace std;

// Base class
class Stack {
protected:
int arr[100], top;
public:
Stack() {
top = -1;
}
void push(int val) {
if (top < 99) {
arr[++top] = val;
}
}
int pop() {
if (top >= 0)
return arr[top--];
else
return -1;
}
};

// Derived class
class EnhancedStack : public Stack {
public:
void display() {
cout << "Stack contents: ";
for (int i = 0; i <= top; i++)
cout << arr[i] << " ";
cout << endl;
}
};

int main() {
EnhancedStack s;
s.push(10);
s.push(20);
s.display();
s.pop();
s.display();
return 0;
}

✅ Explanation:

 Stack is the base class with push and pop


 EnhancedStack adds display()
 Code reuse via inheritance

🔹 6.3 Single Inheritance


One base class → One derived class.
cpp
CopyEdit
class Animal {
public:
void sound() {
cout << "Animal makes sound" << endl;
}
};

class Dog : public Animal {


public:
void bark() {
cout << "Dog barks" << endl;
}
};

✅ Explanation: Dog inherits sound() from Animal.

🔹 6.4 Multiple Inheritance


One derived class inherits from more than one base class.
cpp
CopyEdit
class A {
public:
void showA() { cout << "Class A" << endl; }
};

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

class C : public A, public B {


public:
void showC() { cout << "Class C" << endl; }
};

✅ Explanation: C can use both showA() and showB().

🔹 6.5 Multilevel Inheritance


Derived class inherits from another derived class.
cpp
CopyEdit
class A {
public:
void showA() { cout << "A" << endl; }
};

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

class C : public B {
public:
void showC() { cout << "C" << endl; }
};

✅ Explanation: C can access showA() and showB().

🔹 6.6 Hybrid Inheritance


Combination of multiple and multilevel inheritance.
cpp
CopyEdit
class A {
public:
void showA() { cout << "A" << endl; }
};

class B : public A {};


class C : public A {};
class D : public B, public C {}; // ❌ Ambiguity

❌ Problem: Diamond problem – D has two copies of A.


✅ Solution: Virtual Inheritance
class A {
public:
void showA() { cout << "A" << endl; }
};

class B : virtual public A {};


class C : virtual public A {};
class D : public B, public C {}; // ✅ Fixed

int main() {
D obj;
obj.showA(); // No ambiguity
}

🔹 6.7 Hierarchical Inheritance


Multiple classes inherit from a single base class.
class Parent {
public:
void show() { cout << "Parent class" << endl; }
};

class Child1 : public Parent {};


class Child2 : public Parent {};

✅ Explanation: Both Child1 and Child2 use Parent’s function.

🔹 6.8 Method Overriding


When a derived class redefines a base class function.
class Parent {
public:
void show() {
cout << "Parent show()" << endl;
}
};

class Child : public Parent {


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

✅ Explanation: Child overrides the show() method.

✅ Using virtual for polymorphism:


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

class Child : public Parent {


public:
void show() override {
cout << "Child show()" << endl;
}
};

int main() {
Parent *p = new Child();
p->show(); // Output: Child show()
}

🔹 6.9 UML Modeling of Inheritance


+------------+
| Animal |
+------------+
| +sound() |
+------------+
/ \
/ \
+--------------+ +-------------+
| Dog | | Cat |
+--------------+ +-------------+
| +bark() | | +meow() |
+--------------+ +-------------+

✅ Explanation: UML shows inheritance visually.

🔹 6.10 Summary Table


Type Description
Single One base → one derived
Multiple One derived ← two base
Multilevel Chain of inheritance
Hybrid Combination (may cause diamond problem)
Hierarchical One base → many derived
Virtual Solves ambiguity in hybrid inheritance

📘 7. Association, Aggregation, and


Composition in C++

🔹 7.1 What is Association?


Definition:
Association is a general relationship between two independent classes where one
class uses or connects with another. It does not involve ownership.

✅ Key Points:

 It shows a "uses-a" relationship.


 Both classes can exist independently.
 One object can associate with many objects.

🔸 Example: Teacher and Department


class Department {
public:
string name;
Department(string n) : name(n) {}
};

class Teacher {
public:
string t_name;
Teacher(string name) : t_name(name) {}
void assignDepartment(Department& dept) {
cout << t_name << " works in " << dept.name << " department.\
n";
}
};

int main() {
Department d("Computer Science");
Teacher t("Khadija");
t.assignDepartment(d);
return 0;
}

✅ Explanation:

 Teacher is associated with Department.


 But both can exist independently.

🔹 7.2 UML Modeling of Association


+----------+ uses +-------------+
| Teacher | ------------> | Department |
+----------+ +-------------+

🔹 7.3 What is Aggregation?


Definition:
Aggregation is a special form of Association where one class owns a reference to
another class but does not control its lifetime. It is a "Has-A" relationship.

✅ Key Points:

 Whole–part relationship (but part can exist independently).


 Represented in UML by an empty diamond.

🔸 Example: Department and Student


class Student {
public:
string name;
Student(string n) : name(n) {}
};

class Department {
public:
string dept_name;
vector<Student*> students; // Aggregation

Department(string name) : dept_name(name) {}

void addStudent(Student* s) {
students.push_back(s);
}

void showStudents() {
cout << dept_name << " Department Students:\n";
for (auto s : students) {
cout << "- " << s->name << endl;
}
}
};

int main() {
Student s1("Ali");
Student s2("Khadija");

Department cs("Computer Science");


cs.addStudent(&s1);
cs.addStudent(&s2);

cs.showStudents();
return 0;
}

✅ Explanation:

 Department has students.


 Students can exist outside the department too (no ownership).

🔹 7.4 UML Modeling of Aggregation


+---------------+<>----------->+-----------+
| Department | | Student |
+---------------+ +-----------+

(◊ = aggregation)
🔹 7.5 What is Composition?
Definition:
Composition is a stronger form of Aggregation where one class owns and
manages the lifetime of another class. If the container object is destroyed, so is
the contained object.

✅ Key Points:

 Whole–part relationship (part cannot exist without the whole).


 Represented in UML by a filled diamond.

🔸 Example: House and Room


class Room {
public:
string type;
Room(string t) : type(t) {
cout << type << " created.\n";
}
~Room() {
cout << type << " destroyed.\n";
}
};

class House {
private:
Room bedroom;
Room kitchen;
public:
House() : bedroom("Bedroom"), kitchen("Kitchen") {
cout << "House built.\n";
}
~House() {
cout << "House destroyed.\n";
}
};

int main() {
House h;
return 0;
}
✅ Explanation:

 Houseowns Room objects.


 When the house is destroyed, rooms are automatically destroyed.

🔹 7.6 UML Modeling of Composition


+--------+◆----------->+--------+
| House | | Room |
+--------+ +--------+

(◆ = composition)

🔹 7.7 Summary Table


Concept Relationship Lifetime Dependency UML Symbol
Association uses-a No →
Aggregation has-a (weak) No ◇ (empty)
Composition has-a (strong) Yes ◆ (filled)

🔹 7.8 Real-life Examples


Concept Example
Association Doctor and Hospital
Aggregation Department and Teachers
Composition Car and Engine (Engine dies with Car)

🔹 7.9 Extra Tips


 Prefer Association when classes interact but don't depend on each other.
 Use Aggregation when one class manages objects but doesn’t own them.
 Use Composition when one class is fully responsible for other class objects.
 Avoid Composition if objects should exist independently.
📘 8. Polymorphism in C++

🔹 8.1 What is Polymorphism?


Definition:
Polymorphism means “many forms”. In C++, it allows the same function or
operator to behave differently based on the object or data type.

👉 It is used to achieve flexibility and reusability in code.

✅ Key Points:

 Allows us to use a single interface for different types.


 Increases code extensibility and maintainability.
 Two main types:
o Compile-time Polymorphism (Early Binding)
o Run-time Polymorphism (Late Binding)

🔹 8.2 Types of Polymorphism


Type Description Example
Compile- Function Overloading, Operator add(int, int) vs add(float,
time Overloading float)
Base vs Derived method
Run-time Virtual Functions, Function Overriding
calls

🔹 8.3 Virtual Functions


🔸 What is a Virtual Function?

A virtual function is a member function that is declared in the base class and is
overridden in the derived class. It ensures run-time polymorphism.
✅ Syntax:
class Base {
public:
virtual void display() {
cout << "Base class display\n";
}
};

✅ Key Points:

 Use virtual keyword in the base class.


 Enables function overriding.
 Must have at least one base class pointer or reference.

🔹 8.4 Virtual Function Program Example


#include <iostream>
using namespace std;

class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound\n";
}
};

class Dog : public Animal {


public:
void sound() override {
cout << "Dog barks\n";
}
};

int main() {
Animal* a;
Dog d;
a = &d;

a->sound(); // Calls Dog's version


return 0;
}

✅ Output:
Dog barks
✅ Explanation:

 Even though the pointer is of type Animal*, it calls Dog's sound() due to
virtual function and run-time polymorphism.

🔹 8.5 Pure Virtual Functions


🔸 Definition:

A pure virtual function is a virtual function with no body in the base class. It
forces derived classes to override the function.

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

✅ Key Points:

 A class with at least one pure virtual function becomes an Abstract Class.
 You cannot create an object of an abstract class.

🔹 8.6 Pure Virtual Function Program Example


#include <iostream>
using namespace std;

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

class Circle : public Shape {


public:
void draw() override {
cout << "Drawing a Circle\n";
}
};
int main() {
Shape* s;
Circle c;
s = &c;
s->draw();
return 0;
}

✅ Output:
Drawing a Circle

✅ Explanation:

 Shape is an abstract class.


 Circle provides the implementation of the pure virtual draw() function.

🔹 8.7 UML Modeling for Polymorphism


+--------------------+
| Animal |<-------------+
|--------------------| |
| +virtual sound() | |
+--------------------+ |
|
+---------------------+
| Dog |
|---------------------|
| +sound() override |
+---------------------+

🔹 Shows inheritance + overriding + virtual function.

🔹 8.8 Real-life Examples of Polymorphism


Situation Polymorphism Behavior
Drawing Tool draw() works for circle, rectangle, etc.
Payment Method pay() method varies for cash, card
Remote Control button() behaves differently for TV, AC
🔹 8.9 Extra Tips for Polymorphism
 Always use virtual functions when you expect different behaviors in
derived classes.
 Declare destructors as virtual in base classes to avoid memory leaks.
 Pure virtual functions make the base class abstract — great for interfaces.
 You can still define a pure virtual function outside the class if needed.

🔹 8.10 Summary
Feature Virtual Function Pure Virtual Function
Body in base class Optional ❌ Not allowed
Override in derived Optional ✅ Must override
Object creation Allowed ❌ Not allowed

📘 8. Polymorphism in C++

🔹 8.1 What is Polymorphism?


Definition:
Polymorphism means “many forms”. In C++, it allows the same function or operator to behave
differently based on the object or data type.

👉 It is used to achieve flexibility and reusability in code.

✅ Key Points:

 Allows us to use a single interface for different types.


 Increases code extensibility and maintainability.
 Two main types:
o Compile-time Polymorphism (Early Binding)
o Run-time Polymorphism (Late Binding)
🔹 8.2 Types of Polymorphism
Type Description Example
Compile-time Function Overloading, Operator Overloading add(int, int) vs add(float, float)
Run-time Virtual Functions, Function Overriding Base vs Derived method calls

🔹 8.3 Virtual Functions


🔸 What is a Virtual Function?

A virtual function is a member function that is declared in the base class and is overridden in
the derived class. It ensures run-time polymorphism.

✅ Syntax:
class Base {
public:
virtual void display() {
cout << "Base class display\n";
}
};

✅ Key Points:

 Use virtual keyword in the base class.


 Enables function overriding.
 Must have at least one base class pointer or reference.

🔹 8.4 Virtual Function Program Example


#include <iostream>
using namespace std;

class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound\n";
}
};

class Dog : public Animal {


public:
void sound() override {
cout << "Dog barks\n";
}
};

int main() {
Animal* a;
Dog d;
a = &d;

a->sound(); // Calls Dog's version


return 0;
}

✅ Output:

Dog barks

✅ Explanation:

 Even though the pointer is of type Animal*, it calls Dog's sound() due to virtual
function and run-time polymorphism.

🔹 8.5 Pure Virtual Functions


🔸 Definition:

A pure virtual function is a virtual function with no body in the base class. It forces derived
classes to override the function.

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

✅ Key Points:

 A class with at least one pure virtual function becomes an Abstract Class.
 You cannot create an object of an abstract class.

🔹 8.6 Pure Virtual Function Program Example


#include <iostream>
using namespace std;

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

class Circle : public Shape {


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

int main() {
Shape* s;
Circle c;
s = &c;
s->draw();
return 0;
}

✅ Output:

Drawing a Circle

✅ Explanation:

 Shape is an abstract class.


 Circle provides the implementation of the pure virtual draw() function.

🔹 8.7 UML Modeling for Polymorphism


+--------------------+
| Animal |<-------------+
|--------------------| |
| +virtual sound() | |
+--------------------+ |
|
+---------------------+
| Dog |
|---------------------|
| +sound() override |
+---------------------+

🔹 Shows inheritance + overriding + virtual function.


🔹 8.8 Real-life Examples of Polymorphism
Situation Polymorphism Behavior
Drawing Tool draw() works for circle, rectangle, etc.
Payment Method pay() method varies for cash, card
Remote Control button() behaves differently for TV, AC

🔹 8.9 Extra Tips for Polymorphism


 Always use virtual functions when you expect different behaviors in derived classes.
 Declare destructors as virtual in base classes to avoid memory leaks.
 Pure virtual functions make the base class abstract — great for interfaces.
 You can still define a pure virtual function outside the class if needed.

🔹 8.10 Summary
Feature Virtual Function Pure Virtual Function
Body in base class Optional ❌ Not allowed
Override in derived Optional ✅ Must override
Object creation Allowed ❌ Not allowed

📘 8.13 Static Binding vs Dynamic Binding

🔹 A. Static Binding (Early Binding)


✅ Definition:

When the function call is resolved at compile time, it's called static binding.
This happens in function overloading or operator overloading.

✅ Example:
#include <iostream>
using namespace std;
class Greet {
public:
void sayHello() {
cout << "Hello! (No name)\n";
}

void sayHello(string name) {


cout << "Hello, " << name << "!\n";
}
};

int main() {
Greet g;
g.sayHello(); // Output: Hello! (No name)
g.sayHello("Khadija"); // Output: Hello, Khadija!
return 0;
}

✅ Explanation:

 The function sayHello() is overloaded.


 The compiler decides at compile time which function to call.
 This is Static Binding.

🔹 B. Dynamic Binding (Late Binding)


✅ Definition:

When the function call is resolved at run-time, it's called dynamic binding.
This happens through virtual functions and function overriding.

✅ Example:
#include <iostream>
using namespace std;

class Vehicle {
public:
virtual void start() {
cout << "Starting vehicle...\n";
}
};

class Car : public Vehicle {


public:
void start() override {
cout << "Starting car engine...\n";
}
};

int main() {
Vehicle* v;
Car c;
v = &c;
v->start(); // Output: Starting car engine...
return 0;
}

✅ Explanation:

 Vehicle class has a virtual function.


 Car class overrides that function.
 Function call v->start() is decided at run time, depending on actual object
(Car).
 This is Dynamic Binding.

📊 Comparison Table
Feature Static Binding Dynamic Binding
Timing At compile time At run time
Speed Faster Slightly slower
Flexibility Less flexible More flexible
Achieved By Function/Operator Overloading Virtual Functions
Inheritance Needed ❌ No ✅ Yes
Function Type Normal functions Overridden virtual functions

🔹 8.14 Detailed Programming Example of


Polymorphism (All-in-One)
#include <iostream>
using namespace std;

// Base class with virtual function


class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound\n";
}

void category() {
cout << "Animal category\n";
}
};

// Derived class 1
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks\n";
}
void category() {
cout << "Domestic Animal\n";
}
};

// Derived class 2
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows\n";
}
void category() {
cout << "Pet Animal\n";
}
};

int main() {
Animal* a;
Dog d;
Cat c;

// Runtime Polymorphism
a = &d;
a->sound(); // Output: Dog barks
a->category(); // Output: Animal category (not overridden
because not virtual)

a = &c;
a->sound(); // Output: Cat meows
a->category(); // Output: Animal category

return 0;
}
✅ Explanation of Above Program:
Line Behavior Type
a->sound() Calls derived class version Dynamic Binding
a->category() Calls base class version Static Binding

🔹 8.15 Extra Tips to Remember


 Only virtual functions support dynamic binding.
 Non-virtual functions use static binding — even in derived classes.
 Always prefer virtual destructors in base classes when using
polymorphism.
 Use polymorphism to write extendable and flexible code (e.g., plugins, UI
systems, games, etc.).

✅ Final Summary
Concept Main Point
Static Binding Compile-time decision using overloading
Dynamic Binding Run-time decision using overriding & virtual functions
Programming Use Improves flexibility and reusability
Polymorphism Type Compile-time and Run-time

📘 9. I/O Processing in C++

🔹 9.1 What is I/O Processing?


✅ Definition:
I/O (Input/Output) Processing in C++ is used to read data from input devices
(like keyboard or file) and write data to output devices (like screen or file).

In C++, file handling is done through a library called <fstream>, which provides
tools to create, read, write, and update files.

🔹 9.2 IOS File and Its Branches


✅ What is IOS?
ios stands for Input/Output Stream — it is a base class for all
input/output stream classes in C++.
✅ Branches of IOS File Library:
Class Purpose
ifstream Used to read from a file (input stream)
ofstream Used to write to a file (output stream)
fstream Used for both reading and writing

✅ Diagram:
ios
|
---------------------
| | |
ifstream ofstream fstream

🔹 9.3 Modes of File Operation


These modes define how the file should be opened (for reading,
writing, etc.).
✅ Common File Modes in C++:
Mode Description
ios::in Opens file for reading only
ios::out Opens file for writing only
ios::app Opens file and appends data at the end
ios::ate
Opens file and moves control to the end (you can
still edit anywhere)
ios::trunc Deletes the content of file if it already exists

ios::binary
Opens the file in binary mode (instead of text
mode)
You can combine these modes using the bitwise OR | operator.
Example:
fstream file("data.txt", ios::in | ios::out);

🔹 9.4 File Opening and Closing Example


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

int main() {
ofstream outFile("example.txt"); // Open file in
write mode
outFile << "Hello, Khadija!\n"; // Write to file
outFile.close(); // Close the file

string line;
ifstream inFile("example.txt"); // Open file in
read mode
while (getline(inFile, line)) {
cout << line << endl; // Display
contents
}
inFile.close(); // Close the file

return 0;
}

✅ Explanation:
 ofstream is used to create/write the file.
 ifstream is used to read the file.
 getline() reads one line at a time.
 File must always be closed using .close() after use.

🔹 9.5 Important Notes and Tips


 Always check if the file was successfully opened:
if (!inFile) {
cout << "File could not be opened!";
}

 Never forget to close the file — it saves data and prevents


memory issues.
 You can use fstream when you want both read and write
in one object.

✅ Summary Table
Feature Use
ifstream Read data from file
Feature Use
ofstream Write data to file
fstream Read and write
File Modes Control how file is opened
close() Closes the file
getline() Reads a line from file

🔹 9.6 Bonus Tip: Check File Existence


ifstream checkFile("myfile.txt");
if (checkFile) {
cout << "File exists!\n";
} else {
cout << "File does not exist!\n";
}

📘 10. File Processing – Text Filing

🔹 10.1 What is File Processing?


✅ Definition:

File Processing in C++ means reading from or writing to files stored


on your computer. This allows data to be saved permanently (even
after the program ends).
🔹 10.2 What is Text Filing?
✅ Definition:

Text filing is a type of file processing where data is stored in human-


readable format (like .txt files).
You can open these files in Notepad, WordPad, etc.

✅ Uses of Text Filing:

 Saving user records


 Writing logs
 Storing simple databases
 Exporting reports

🔹 10.3 Classes Used for Text Filing in C++


These classes are part of the <fstream> header:

Class Use
ofstream Write to a text file
ifstream Read from a text file
fstream Read and write to file

🔹 10.4 Writing to a Text File (Example)


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

int main() {
ofstream outFile("data.txt"); // Open file for writing

outFile << "Name: Khadija\n";


outFile << "Department: Software Engineering\n";
outFile << "Semester: 2nd\n";
outFile.close(); // Always close the file

cout << "Data written to file successfully.\n";


return 0;
}

✅ Explanation:

 ofstream outFile("data.txt"); → creates or opens a file named


data.txt in write mode.
 << is used to write data to the file.
 .close() is used to save and close the file.

🔹 10.5 Reading from a Text File (Example)


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

int main() {
ifstream inFile("data.txt"); // Open file for reading
string line;

while (getline(inFile, line)) {


cout << line << endl; // Print each line from file
}

inFile.close(); // Always close the file

return 0;
}

✅ Explanation:

 ifstream is used to open the file for reading.


 getline() reads the file line-by-line.
 The file must be closed using .close().
🔹 10.6 Checking if File Exists
ifstream file("data.txt");
if (!file) {
cout << "File not found!" << endl;
} else {
cout << "File is ready." << endl;
}

🔹 10.7 Common File Modes for Text Filing


Mode Description
ios::out Create or overwrite file
ios::app Append data to end of file
ios::in Open file for reading
ios::ate Open and move to end (editable)
ios::trunc Delete contents before writing

✅ Summary Table
Task Class Description
Write to text file ofstream Sends data to a file
Read from file ifstream Reads data from a file
Both read & write fstream Dual-purpose file handling
Store as plain text Text filing Human-readable storage format

🔹 10.8 Extra Tips for Text Filing


 Always close the file to avoid data loss.
 Always check if the file opened successfully using if (!file)
condition.
 File paths must be correct (especially when not in the same folder
as your .cpp file).
📘 11. Exception Handling in C++

🔹 11.1 What is Exception Handling?


✅ Definition:

Exception handling is a mechanism used to handle errors and unusual


situations that occur during program execution without crashing the
program.

It allows the program to:

 Detect runtime errors


 Catch and handle them properly
 Continue executing the rest of the code smoothly

🔹 11.2 Why Use Exception Handling?


✅ Importance:

 To avoid program crash when an error occurs (e.g., divide by


zero, file not found).
 To write safe and secure programs.
 To separate error-handling code from regular code.

🔹 11.3 Keywords Used in Exception Handling


Keyword Use
try Defines a block of code to be tested for errors (risky code).
throw Used to throw an exception (an error condition).
catch Defines a block of code that handles the error (exception).

🔹 11.4 Syntax of Exception Handling


try {
// Code that may cause an error
throw value; // Throwing an exception
}
catch (type variable) {
// Code to handle the exception
}

🔹 11.5 Program Example – Division by Zero


#include <iostream>
using namespace std;

int main() {
int a = 10, b = 0;

try {
if (b == 0)
throw "Division by zero error!";
cout << "Result: " << a / b << endl;
}
catch (const char* msg) {
cout << "Exception Caught: " << msg << endl;
}

cout << "Program continues after exception." << endl;


return 0;
}

✅ Explanation:

 try block contains risky code.


 If b == 0, the code throws an exception using throw.
 The catch block catches the exception and handles it by displaying
a message.
 The program does not crash and continues running.

🔹 11.6 Multiple Catch Blocks


You can handle different types of exceptions:
try {
throw 10; // or throw "error";
}
catch (int x) {
cout << "Integer Exception: " << x << endl;
}
catch (const char* msg) {
cout << "String Exception: " << msg << endl;
}

🔹 11.7 Catching All Exceptions


try {
throw 3.14;
}
catch (...) {
cout << "Caught an unknown exception!" << endl;
}

🔹 11.8 Summary Table


Term Description
try Block where risky code is written
throw Used to raise an exception
catch Handles the exception
... Catches any type of exception (generic)
🔹 11.9 Extra Tips
 Always write the catch block after try.
 Catch blocks should match the type of exception thrown.
 You can throw custom data types (like classes or structs) as
exceptions.
 Exception handling only handles runtime errors, not compile-
time errors.

You might also like