Lecture 1 – Introduction to Object-Orientation (OO)
1.1 What is Object-Orientation?
Object-Orientation is a technique used to solve real-world problems in programming by thinking
in terms of objects and their interactions, just like in real life.
Real-life Examples of Objects:
Ali (a person)
Car
House
Tree
These objects interact with each other:
Ali lives in a house
Ali drives a car
School Example:
Objects in a school:
Student, Teacher, Book, Pen, Bag, Parents, Classroom, Playground
For a fee collection system, we think about related objects (Student, Accounts, Fee) and how
they interact — this helps design the system more naturally.
✅ Key Point: OO helps us solve problems by thinking in terms of real-life objects.
1.2 What is a Model?
A model is a simplified representation (abstraction) of a real or conceptual thing.
Examples of Models:
Highway maps
Building models (architecture)
Mechanical designs
✅ We use models to understand reality and to simplify complex systems.
1.3 Object-Oriented Models (OO Models)
In programming, OO models help us understand a problem before developing it by showing
objects and their interactions.
Example 1:
Objects: Ali, House, Car, Tree
Interactions:
o Ali lives in House
o Ali drives Car
Example 2 (School Model):
Objects: Teacher, Student, Book, Pen, Bag, Playground
Interactions:
o Teacher teaches Student
o Student has Book, Pen, and Bag
✅ OO Models make it easier to understand and design systems.
1.4 Advantages of Object-Orientation
Easy to understand because it's based on real-life.
Easy to design using OO models.
Easy to implement using OO programming languages (like C++).
Supports concepts like classes, inheritance, polymorphism etc.
1.5 What is an Object?
An object is:
Tangible (real): like Ali, Car, House
Intangible (conceptual): like Time, Date
An Object has:
1. State (attributes): Describes the object (e.g., color, name)
2. Behavior (operations): What it can do (e.g., drive, walk)
3. Unique Identity: Every object is uniquely identified.
1.6 Tangible vs Intangible Objects
Object Attributes (State) Behavior (Operations)
Ali (Tangible) Name, Age Walks, Eats
Car (Tangible) Color, Model Accelerates, Starts
Time (Intangible) Hours, Minutes Set/Get time
Date (Intangible) Day, Month, Year Set/Get date
1.7 Summary
A Model is an abstraction that helps us understand a real-world problem.
OO Models show problems in terms of objects and their relationships.
OO programming is easier to relate to real life and makes development simpler.
Object = Data (attributes) + Functions (behavior)
Objects can be real (tangible) or conceptual (intangible).
Nouns in problem descriptions are often candidates for objects.
Some objects may not have a role in implementation (e.g., school parking).
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Lecture 2 – Information Hiding, Encapsulation & Related Concepts
02.1 Information Hiding
Definition:
Information Hiding is the principle of exposing only what is necessary to the outside world while
keeping all other details hidden. In OOP, this means an object’s internal state and private methods are
not directly accessible by other objects or classes.
Real-Life Examples:
1. Personal Secrets: Ali’s memories and private data are stored in his mind. You can only learn
them by asking Ali—and he chooses how much to reveal.
2. Email Server: Though it holds millions of accounts, it reveals only your own mailbox. Any request
for someone else’s mailbox is refused.
3. SIM Card: It contains all stored numbers, but you see them only through your phone’s UI—and
only if the phone owner allows it.
In OOP: Each object “owns” its data and only shares it via well-defined methods.
Why It Matters:
Simplifies Models: By hiding inner workings, OO models show only objects and their
interactions, making diagrams and designs clearer.
Reduces Change Impact: Since callers know only method signatures, you can change internal
logic without affecting other parts of the system.
How It’s Achieved:
Primarily via Encapsulation (bundling data + behavior) and Abstraction (exposing only essential
features).
02.2 Encapsulation
Definition:
Encapsulation means wrapping an object’s data (attributes) and behavior (methods) together, with all
internal details hidden inside the object.
“An object is a black box: you see only its interface; you don’t see its insides.”
Relation to Information Hiding:
Encapsulation is the mechanism through which we achieve information hiding.
Example (Ali):
Data Members: name, age
Methods: walk(), eat()
Both are contained within the “Ali” object. No other object can directly modify Ali’s age—it must
call, say, Ali.setAge(newAge).
Example (Phone):
Data Members: contact list stored on SIM
Methods: placeCall(number), addContact(name, number)
The phone UI and internal storage are bundled; you interact via phone’s methods only.
Advantages:
1. Simplicity & Clarity: Every piece of data or function belongs to exactly one object—no loose,
global functions or variables.
2. Lower Complexity: You trace behavior within one object at a time—methods don’t unexpectedly
call into hidden globals.
3. Better Understanding: Object diagrams fully describe each object’s role and relations; nothing is
hidden in scattered code.
02.3 Interface
Definition:
The interface of an object is the set of public methods it exposes for other objects to call. It’s the
object’s “contract” with the outside world.
Objects may offer different interfaces to different clients, but the simplest view is “public vs.
private” methods.
Examples:
Object Public Interface Methods
Car steer(direction), accelerate(amount), brake(), turnLights(onOff)
Phone dial(number), hangUp(), addContact(name, number), deleteContact(id)
Objects communicate only via interfaces—no direct field access.
02.4 Implementation
Definition:
Implementation is the actual code or mechanism that realizes an object’s behavior. It consists of:
1. Internal Data Structures to maintain state (e.g., private fields).
2. Member Functions that use those structures to provide functionality.
Example a) Gearbox in a Car System
Data Structure: Gears, shafts, linkages.
Functionality: Code/mechanism to shift gears when changeGear(position) is called.
Example b) Address Book in a Phone
Data Structure: SIM card memory blocks holding name/number pairs.
Functionality: Methods like readContact(id) and writeContact(name, number) that interact with
the SIM.
02.5 Separation of Interface & Implementation
Concept:
You present only the interface to users; you hide the implementation. This clear boundary ensures:
Flexibility: You can rewrite or optimize internals without breaking client code.
Maintainability: Clients depend only on stable method signatures.
Real-Life Analogy:
Every car has a standard interface—steering wheel, pedals, gear shifter—so any driver can operate any
car model, regardless of its engine type or internal mechanisms.
02.6 Messages
Definition:
Objects interact by sending messages (invoking methods) to each other, using the recipient’s interface.
The message includes the method name and any parameters.
The recipient processes the message via its implementation.
Examples:
“Stop!” message: User calls car.brake() → Car object executes its brake() method.
“Place Call” message: User calls phone.dial("+123456789") → Phone object executes dialing
routine.
In diagrams, arrows between objects represent message sends.
02.7 Summary
Information Hiding: Show only what’s necessary; hide private details.
Encapsulation: Bundle data + methods; the vehicle for hiding.
Interface: The public face of an object—its available methods.
Implementation: The hidden workings behind each method.
Separation: Clients see only interface; internals can evolve freely.
Messages: Method calls between objects—how they communicate.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Lecture 3 – Abstraction, Classes, Inheritance,
and Benefits of Inheritance
03.1 Abstraction
What is Abstraction?
In real life, objects have many attributes (data) and behaviors (actions), but often we focus only
on the aspects relevant to the current problem we want to solve.
Example:
If we are designing a school management system, we do not care about the personal life of
students or teachers, only the details related to the school system like their student ID, courses,
grades, teaching assignments, etc.
This concept of focusing only on relevant details and ignoring the rest is called Abstraction.
Principle of Abstraction
“Capture only those details about an object that are relevant to the current perspective.”
Abstraction Example: Object "Ali"
Ali is both a PhD student and a teacher. Depending on which perspective we take, his attributes
and behaviors differ.
Attributes Student Perspective Teacher Perspective
Name Yes Yes
Age Yes Yes
Student Roll No Yes No
Year of Study Yes No
CGPA Yes No
Employee ID No Yes
Designation No Yes
Attributes Student Perspective Teacher Perspective
Salary No Yes
Behaviors Student Perspective Teacher Perspective
Study Yes No
Develop Exam No Yes
Give Exam Yes Yes
Take Exam Yes No
Play Sports Yes No
Eat Yes Yes
Deliver Lecture No Yes
Walk Yes Yes
This means Ali’s student and teacher roles are abstractions that highlight different attributes
and behaviors while ignoring the rest.
More Examples of Abstraction
Cat:
o Ordinary person’s view: a pet with four legs and a tail
o Surgeon’s view: skeleton, heart, organs, etc.
Car:
o Driver’s perspective: steering wheel, pedals, speedometer
o Engineer’s perspective: engine parts, fuel injection system, wiring
Advantages of Abstraction
1. Simplifies understanding and problem solving by hiding irrelevant details.
2. Allows changing implementation details in one perspective without affecting others.
3. Helps achieve information hiding, showing only relevant details to related objects.
03.2 Classes
What is a Class?
A class is a blueprint or prototype from which objects are created. It defines the common
structure (attributes) and behavior (methods) that all objects of that type share.
Multiple objects (instances) of the same class share the same structure and behavior but
hold their own unique data.
Examples of Classes and Instances
Example 1: Students
Object Class
Ali Student
Anam Student
Sohail Student
Example 2: Teachers
Object Class
Ahsan Teacher
Aamir Teacher
Atif Teacher
Class Representation (UML notation)
Normal Form: Rectangle divided into three sections
1. Class Name
2. Attributes (data members)
3. Operations (methods)
Example: Circle Class
Circle (Class Name) Attributes Operations
center, radius draw(), computeArea()
Example: Person Class
Person (Class Name) Attributes Operations
name, age, gender walk(), eat()
03.3 Inheritance
What is Inheritance?
Inheritance allows a child class (derived class) to inherit attributes and behaviors from a parent
class (base class).
The child class has all the properties of the parent and can also add its own unique
properties.
Inheritance Relationships — “IS A” or “IS A KIND OF”
A Student IS A Person
A Teacher IS A Person
A Doctor IS A Person
A Circle IS A Shape
A Triangle IS A Shape
A Line IS A Shape
Example: Person Class and Derived Classes
Class Attributes Methods
Person name, age, gender eat(), walk()
Student program, studyYear study(), heldExam()
Teacher designation, salary teach(), takeExam()
Doctor designation, salary checkUp(), prescribe()
Example: Shape Class and Derived Classes
Class Attributes Methods
Shape color, coord draw(), rotate(), setColor()
Circle radius draw(), computeArea()
Line length draw()
Triangle angle draw(), computeArea()
Advantages of Inheritance
1. Reuse:
You can reuse existing code and add or override only what is new or different.
2. Less Redundancy:
No need to rewrite common code in multiple classes.
3. Increased Maintainability:
Changes in the base class automatically propagate to derived classes, making
maintenance easier.
How Reuse Works with Inheritance
Select an existing class close to your desired functionality.
Create a new class derived from that base class.
Add new attributes or methods or modify existing ones as needed.
Summary of Lecture 3
Concept Description
Abstraction Focusing on relevant attributes and behaviors, ignoring others.
Class Blueprint for creating objects with common attributes and methods.
Mechanism to create new classes from existing classes, inheriting
Inheritance
properties and behaviors.
Benefits of
Reuse code, reduce redundancy, increase maintainability.
Inheritance
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Lecture 04: Inheritance – Advanced Concepts
Key Concepts Covered
Generalization
Subtyping (Extension)
Specialization (Restriction)
Overriding
Abstract Classes
Concrete Classes
🔁 Recap: Inheritance
Inheritance lets a derived class inherit characteristics from a base class.
Benefits: Code reuse and better organization.
🔹 04.1 Generalization
Definition: Combining shared features from multiple classes into a general/base class.
Common in objects that have similar behavior/attributes.
Relationship: "Is a kind of" (e.g., Circle is a kind of Shape).
Example:
text
CopyEdit
Circle, Triangle, Line → all inherit from → Shape
Doctor, Teacher, Student → all inherit from → Person
🔹 04.2 Subtyping (Extension)
Definition: A derived class extends the behavior of a base class.
Derived class is behaviorally compatible (can replace base class).
Example:
text
CopyEdit
Student has all features of Person + extra features like study(), takeExam()
Circle extends Shape by adding radius, computeArea()
Top to Bottom View (from general to specific).
🔹 04.3 Specialization (Restriction)
Definition: Derived class restricts or changes some behavior of base class.
Derived class is not behaviorally compatible with base.
Example:
text
CopyEdit
Adult class (derived from Person) allows only age > 18.
NaturalSet (derived from IntegerSet) only allows positive numbers.
Bottom to Top View (from specific to general).
🔹 04.4 Overriding
Definition: Derived class redefines a method of its base class.
Reasons:
o Provide specific behavior
o Extend base behavior
o Restrict behavior
o Improve performance
Example:
text
CopyEdit
Shape class has draw()
Circle overrides draw() with its own version
DialogBox overrides draw() to first call Window’s draw, then draw itself
🔹 04.5 Abstract Classes
Represent abstract ideas (like Shape, Person, Vehicle).
Can't be instantiated (no objects of abstract classes).
Provide base behavior to be inherited.
Examples:
Abstract: Shape → Concrete: Circle, Line, Triangle
Abstract: Person → Concrete: Student, Doctor, Teacher
🔹 04.6 Concrete Classes
Represent real-world entities.
Can be instantiated.
Exist independently in object models.
Examples:
Student, Doctor, Car, Bus, Truck
✅ Quick Definitions
Term Meaning
Generalization Common features moved to a base class
Subtyping Derived class adds extra behavior
Specialization Derived class restricts or changes some base behavior
Overriding Redefining a base method in the derived class
Abstract Class A class that can't be instantiated, only meant to be inherited
Concrete Class A fully implemented class you can create objects from
Here's a complete and simplified summary of Lecture No. 05 – Multiple Inheritance from
CS304 (Object Oriented Programming), ensuring no point is missed:
📘 Lecture 05 Summary: Multiple Inheritance
🔁 Inheritance Recap
Purposes of Inheritance:
o Generalization
o Extension/Sub-typing
o Specialization/Restriction
Class Types:
o Abstract Classes → for abstract concepts
o Concrete Classes → for real objects
Overriding: Allows derived class to redefine base class methods for:
o Specialization
o Extension
o Restriction
o Performance
05.1 Multiple Inheritance
🔹 Definition
A class inherits from more than one base class.
Used when a class needs features of multiple parent classes.
🧜 Example 1: Mermaid (inherits from Woman & Fish)
class Fish { public: void swim(); };
class Woman { public: void walk(); };
class Mermaid : public Woman, public Fish {};
Mermaid can both walk() and swim() using features from both classes.
🚙 Example 2: Amphibious Vehicle
Inherits from LandVehicle and WaterVehicle, both inherit from Vehicle.
Amphibious vehicle can:
o changeGear() from Vehicle
o Float() from WaterVehicle
o Move() from LandVehicle
✅ Advantages of Multiple Inheritance
Code Reusability: Inherit from multiple classes without repeating code.
⚠️Disadvantages of Multiple Inheritance
1. Increased Complexity
More difficult to understand and maintain.
2. Reduced Understanding
Object model becomes harder to grasp for new developers.
3. Duplicate Features
Problem 1: Ambiguity
If both parent classes have same method (eat() in Woman and Fish), compiler doesn’t
know which one to use.
✔️Solution: Override in Derived Class
class Mermaid : public Woman, public Fish {
public:
void eat() {
Woman::eat(); // or Fish::eat()
}
};
Problem 2: Diamond Problem
AmphibiousVehicle inherits changeGear() from both LandVehicle and WaterVehicle
(both from Vehicle).
Results in two copies of changeGear().
Causes ambiguity error: request for member 'changeGear' is ambiguous.
✔️Solution:
Use virtual inheritance (discussed in future lectures).
Some languages restrict diamond inheritance or provide mechanisms to handle it.
🤝 Association
Definition
Interaction between objects in OO model to perform a task.
Represented by lines (with or without arrowheads).
05.2 Types of Association
1. Class Association
Done via inheritance.
Public Inheritance → IS-A relationship.
Private Inheritance → “implemented in terms of”.
2. Object Association
Interaction between independent objects (no inheritance).
05.3 Simple Association
Definition
Weakest link; objects interact without strong relationship.
Examples:
Ali lives in House
Customer gets cash from cashier
Types of Simple Association
a. By Navigation (Direction):
One-way Association → single direction (arrow)
Two-way Association → both directions (line)
b. By Cardinality (Number of Objects):
Binary Association → two classes (e.g. Ali drives Car)
Ternary Association → three classes
N-ary Association → more than three (rare)
05.4 Composition
Definition
"Part-of" relationship
Strong link: Parts can’t exist independently.
Examples:
Ali is composed of Body parts (Head, Arm, Leg)
Chair is composed of Seat, Legs, Arms
Representation:
Line with filled diamond towards whole.
05.5 Aggregation
Definition
"Has-a" relationship
Weaker than composition: parts can exist independently.
Examples:
Room has Furniture (furniture can move)
Garden has Plants (plants can be replanted)
Representation:
Line with empty diamond towards container.
✅ Key Differences: Composition vs Aggregation
Feature Composition Aggregation
Strength Strong Weak
Part of Whole? Yes No
Independent? Cannot exist independently Can exist independently
Notation Filled diamond Empty diamond
Let me know if you want MCQs, short questions, or flashcards from this lecture!
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
🔍 Lecture 06 Summary (Simplified)
✅ 06.1 Class Compatibility
If one class supports all the operations of another class, it is behaviorally compatible
(called a subtype).
A derived class is usually a subtype of its base class.
So, base class can be replaced by derived class safely.
Example:
cpp
CopyEdit
class Shape {
public:
void draw();
void setColor();
};
class Circle : public Shape {
public:
void computeArea();
};
Shape* s = new Circle(); // This is valid (Class Compatibility)
✅ All these are compatible with Shape:
Line
Circle
Triangle
✅ 06.2 What is Polymorphism?
Polymorphism means “many forms”.
In OOP, it means same function call behaves differently for different objects.
Real-life example:
Coal and Diamond are different forms of Carbon.
✅ 06.3 Polymorphism in Object-Oriented Model
A message (function call) can be sent without knowing the exact class.
The receiver object handles the message according to its type.
Example:
cpp
CopyEdit
Shape* s;
s = new Line(); // s->draw() → Line's draw
s = new Circle(); // s->draw() → Circle's draw
✅ Benefits:
Easy to add new classes.
Reduces code changes.
Increases reusability and flexibility.
✅ 06.4 Example: Graphic Editor
Problem: A graphic editor should draw shapes (line, circle, triangle). User can select, move,
rotate, and group shapes.
✅ Class Identification:
Extracted from nouns:
Shape (base class)
Line, Circle, Triangle (inherited from Shape)
Group (group of shapes)
Menu
View
✅ Associations:
1. Composition:
o Group has Shapes (line, circle, etc.)
2. Aggregation:
o View contains Shapes
3. Simple Association:
o Menu sends command to View
✅ Attributes of Classes:
Class Attributes
Shape color, vertices
Line length
Circle radius
Triangle angle
Group noOfObjects
View noOfObjects, selected
Menu name, isOpen
✅ Operations of Classes:
Class Operations
Shape draw, select, move, rotate
Line draw, select, move, rotate
Circle draw, select, move, rotate
Triangle draw, select, move, rotate
Group draw, select, move, rotate
View add, remove, group, show, select, move, rotate
Menu open, select, move, rotate
✅ Inheritance:
Shape is the parent of Line, Circle, Triangle, and Group.
All derived classes override draw().
📘 Lecture 06 – Class Compatibility and Polymorphism
🔶 06.1 Class Compatibility
✅ Definition:
If a derived class (child class) supports all the behaviors (operations) of its base class
(parent class), then it is behaviorally compatible.
Such a class is known as a subtype.
You can safely replace a base class object with its subtype.
✅ Example:
cpp
CopyEdit
class Shape {
public:
void draw() {
cout << "Drawing shape..." << endl;
}
};
class Circle : public Shape {
public:
void computeArea() {
cout << "Area of circle" << endl;
}
};
// Using Circle where Shape is expected
Shape* s = new Circle(); // Valid: Circle is compatible with Shape
s->draw(); // Calls draw() from Shape
✅ Urdu Explanation:
Agar aik class (Circle) apni base class (Shape) ki tamam functionalities perform kar sakti
hai, tou woh us base class ka subtype kehlayegi. Iska matlab hai k Shape ki jagah Circle
ka object use ho sakta hai.
🔶 Examples of Class Compatibility
Base Class: Shape
less
CopyEdit
Attributes: color, vertices
Methods: move(), setColor(), draw()
Derived Classes:
Circle → radius, draw(), computeArea()
Line → length, draw(), getLength()
Triangle → angle, draw(), computeArea()
✅ All above classes override or extend the base functionality. Hence, they are
behaviorally compatible with Shape.
🔷 06.2 What is Polymorphism?
✅ Definition:
Polymorphism means “many forms”. In programming, it allows same function name to
behave differently based on the object calling it.
✅ Urdu Explanation:
Polymorphism ka matlab hai aik hi function mukhtalif objects par alag tareeqay se kaam
kare. Jaise coal aur diamond dono Carbon hain, lekin unki shaklein aur istimaal alag hain.
🔷 06.3 Polymorphism in Object-Oriented Model
✅ OOP Behavior:
Message is sent to object, actual class decides how to respond.
No need to know the exact class of object.
✅ Example:
cpp
CopyEdit
class Shape {
public:
virtual void draw() {
cout << "Drawing shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing circle" << endl;
}
};
class Triangle : public Shape {
public:
void draw() override {
cout << "Drawing triangle" << endl;
}
};
void render(Shape* s) {
s->draw(); // Will call draw() of actual class
}
Output:
If s is Circle → Drawing circle
If s is Triangle → Drawing triangle
🔶 Real-world Analogy:
print() function is called by an editor.
If the object is:
ASCII File → prints in ASCII format.
PDF File → prints in PDF format.
PS File → prints in PostScript format.
🟩 Function is same (print()), behavior changes based on object type.
🔶 06.4 Advantages of Polymorphism
Same function can act differently.
New classes can be added without modifying existing code.
Supports flexibility and code reuse.
✅ Urdu Example:
Agar apke paas aik draw() function hai, toh chahe object Circle ho ya Triangle, function
ka naam same hoga, lekin kaam alag hoga. Yeh flexibility deta hai system mein naye
objects ko asani se shamil karne ki.
🔷 06.5 Object-Oriented Modeling – Example: Graphic Editor
🔹 Problem Statement:
Design a graphic editor that:
Draws different shapes: Line, Circle, Triangle
Allows user to: select, move, rotate
User can group multiple shapes
Editor has a menu for commands
🔹 Step-by-Step Object Modeling
Step 1: Identify Classes
From nouns:
Shape
Line
Circle
Triangle
Menu
Group
View
❌ Irrelevant:
Editor (too broad)
User (outside system boundary)
✅ Final Classes:
Shape
Line (inherits from Shape)
Circle (inherits from Shape)
Triangle (inherits from Shape)
Group (inherits from Shape)
Menu
View
✅ Step 2: Identify Associations
Group has shapes (Line, Circle, etc.) → Composition
Group can contain other groups → Recursive Composition
View contains shapes → Aggregation
Menu sends commands to View → Association
🔶 Step 3: Attributes of Classes
Class Attributes
Shape color, vertices
Line length
Circle radius
Triangle angle
Group noOfObjects
View noOfObjects, selected
Menu name, isOpen
🔶 Step 4: Operations of Classes
Class Operations
Shape draw(), select(), move(), rotate()
Line draw(), select(), move(), rotate()
Circle draw(), select(), move(), rotate()
Triangle draw(), select(), move(), rotate()
Class Operations
Group draw(), select(), move(), rotate()
View add(), remove(), group(), show(), select(), move(), rotate()
Menu open(), select(), move(), rotate()
🔶 Step 5: Inheritance Identification
Line, Circle, Triangle → Inherit from Shape
Group → Behaves like a Shape → Also inherits from Shape
📈 Text-Based Object Model Diagram
pgsql
CopyEdit
+----------------+
| Shape |
| color, vertices|
| draw(), move() |
| select(), rotate()|
+----------------+
/ | \ \
/ | \ \
/ | \ \
+--------+ +--------+ +----------+ +----------+
| Line | | Circle | | Triangle | | Group |
| length | | radius | | angle | |noOfObjs |
| draw() | | draw() | | draw() | | draw() |
+--------+ +--------+ +----------+ +----------+
+------------+
| View |
| noOfObjs |
| selected |
| add(), remove(), group() |
+------------+
+------------+
| Menu |
| name |
| isOpen |
| open(), move() |
+------------+
📌 Conclusion
Class Compatibility → Replace base with derived safely.
Polymorphism → Same function name, different behavior.
Object-Oriented Design → Helps build scalable and flexible systems.
Example of Graphic Editor shows real-world modeling using OOP.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
🎓 Lecture 07: Class and Object
Course: CS304 – Object-Oriented Programming
Topic: Realization of Objects using Class in C++
✅ Lecture Summary (Simplified in Urdu):
🔹 Object Orientation ka Asal Concept: "Object"
Object ka matlab hai koi bhi real-life cheez jiska kuch data (attributes) aur kuch
functions (behaviors) hoon.
C++ mein class ka istemal object ko program mein banane ke liye kiya jata hai.
🔹 Class kya hoti hai?
Class ek blueprint ya template hota hai jisme hum object ke data (attributes) aur
behavior (functions) ko define karte hain.
Yeh C++ ka mechanism hai taake hum apne custom types bana sakein jaise Student,
Circle, etc.
🔹 Misal (Example):
Jese har lion mein kuch common features hotay hain, waise hi har student mein kuch common
attributes (name, roll no, degree) aur behaviors (study, register) hotay hain.
🔹 Real Life Mimicry:
Object Oriented Programming real life ko mimic karti hai:
Student object → Teacher object se help leta hai.
Classroom object, Subject object se related hota hai.
🧱 07.1 – Class and Object Key Concepts
Term Description (Simplified)
Class User-defined type; data + functions ka group
Object Class ka ek real instance (e.g. aStudent)
Data Members Object ke attributes (e.g. name, age)
Member Functions Object ke actions (e.g. setName())
Instantiation Object banana (Student aStudent;)
Dot Operator . Object ke members ko access karne ke liye
Arrow Operator -> Object pointer ke members ko access karne ke liye
Setters/Getters Functions to safely access private data
📌 07.2 – User Defined Types in C++
Built-in types: int, float
Custom types: class Student, class Circle
Class banake hum apni types define karte hain.
🔒 07.3 – Abstraction ()تجرید
Sirf wahi data include karte hain jo system ke liye zaroori ho.
Extra cheezain (e.g. sibling, fatherBusiness) ko skip karte hain.
🧱 07.4 – Class Definition Syntax
cpp
CopyEdit
class Student {
private:
int rollNo;
char *name;
float CGPA;
public:
void setName(char *newName);
void setRollNo(int newRollNo);
};
💡 Why use Member Functions?
Behaviors ko define karne ke liye
Data hiding implement karne ke liye
Validation karne ke liye (e.g. negative roll number se bachne ke liye)
🆚 07.5 – Object vs Class
Feature Class Object
Kya hai? Blueprint Instance
Purpose Define structure Hold data
Example class Student {} Student aStudent;
🚪 07.6 – Accessing Members
cpp
CopyEdit
Student aStudent;
aStudent.setRollNo(5); // dot operator
Student *ptr = new Student();
ptr->setRollNo(10); // arrow operator
🛑 Note: Data members ko direct access nahi karna chahiye (aStudent.rollNo = 5;) — setter
function use karo.
🔐 07.7 – Access Specifiers
Specifier Access
private Only class ke andar accessible
public Class ke bahar se accessible
protected (Inheritance mein detail se discuss hoga)
Default: Agar koi access specifier na diya ho to members private hote hain.
🧪 Example Code with Setters
cpp
CopyEdit
class Student {
private:
char *name;
int rollNo;
public:
void setName(char *aName) {
if(strlen(aName) > 0) {
name = new char[strlen(aName) + 1];
strcpy(name, aName);
}
}
void setRollNo(int aNo) {
if(aNo > 0)
rollNo = aNo;
}
};
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Lecture 08: Member Functions and Constructors
🔹 08.1 Member Functions
Functions inside a class that access or modify its data.
Public member functions act as the interface to the outside world.
🔹 08.2 Defining Member Functions
🔸 a) Inside the class (automatically inline):
cpp
CopyEdit
class Student {
int rollNo;
public:
void setRollNo(int aRollNo) {
rollNo = aRollNo;
}
};
🔸 b) Outside the class:
In header file (.h):
cpp
CopyEdit
class Student {
int rollNo;
public:
void setRollNo(int aRollNo);
};
In implementation file (.cpp):
cpp
CopyEdit
void Student::setRollNo(int aRollNo) {
rollNo = aRollNo;
}
🔹 08.3 Inline Functions
Inline function = Compiler replaces function call with function code (for speed).
Use keyword inline (compiler may ignore).
Functions inside class are automatically inline.
cpp
CopyEdit
inline int Area(int len, int height) {
return len * height;
}
🔹 08.4 Constructor
Special function with same name as class.
No return type.
Automatically called when object is created.
cpp
CopyEdit
class Student {
int rollNo;
public:
Student() {
rollNo = 0;
cout << "Constructor called\n";
}
};
🔹 08.5 Default Constructor
No parameters or all parameters have default values.
If not defined, compiler creates one (implicit).
If you define any constructor, compiler will not create a default one.
🔹 08.6 Constructor Overloading
More than one constructor with different parameters.
cpp
CopyEdit
class Student {
int rollNo;
char* name;
float GPA;
public:
Student(); // No argument
Student(char* aName); // 1 argument
Student(char* aName, int aRollNo); // 2 arguments
Student(char* aName, int aRollNo, float aGPA); // 3 arguments
};
Better way (using default values):
cpp
CopyEdit
Student(char* aName = NULL, int aRollNo = 0, float aGPA = 0.0);
🔹 08.7 Copy Constructor
Used when:
o One object is initialized with another.
o Object is passed by value to a function.
Student(const Student& obj) {
rollNo = obj.rollNo;
name = obj.name; // Shallow Copy
GPA = obj.GPA;
}
🔹 08.8 Shallow Copy
Copies pointers as they are → both objects point to same memory.
Problem: If one object is deleted, the other has a dangling pointer.
🔹 08.9 Deep Copy
Allocates new memory and copies actual data.
Fixes shallow copy problem.
cpp
CopyEdit
Student(const Student& obj) {
int len = strlen(obj.name);
name = new char[len + 1];
strcpy(name, obj.name); // Deep Copy
rollNo = obj.rollNo;
GPA = obj.GPA;
}
🔹 Lecture 08: Member Functions & Constructors (Summary
Notes)
08.1 Member Functions
Functions that operate on class data.
Public member functions provide the interface to use the class.
08.2 Defining Member Functions
Two ways to define:
1. Inside the class
cpp
CopyEdit
class Student {
int rollNo;
public:
void setRollNo(int aRollNo) {
rollNo = aRollNo;
}
};
2. Outside the class
o Declare in class, define using scope resolution :: outside.
cpp
CopyEdit
class Student {
int rollNo;
public:
void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo) {
rollNo = aRollNo;
}
08.3 Inline Functions
Replaces function calls with actual code to save time.
Use inline keyword.
Small functions often declared as inline.
Inside class = automatically inline
Outside class = use inline keyword manually
cpp
CopyEdit
inline int Area(int len, int hi) {
return len * hi;
}
08.4 Constructor
Special function to initialize objects.
Auto-called when object is created.
Name = class name, No return type.
08.5 Constructor Properties
Public
Automatically called at object creation
Helps put object in a valid state
cpp
CopyEdit
class Student {
int rollNo;
public:
Student() {
rollNo = 0;
cout << "Constructor called";
}
};
08.6 Default Constructor
No parameters or all parameters have default values.
Compiler creates implicit default constructor if none is defined.
cpp
CopyEdit
Student(); // explicit (user-written)
08.7 Constructor Overloading
Multiple constructors with different parameters.
cpp
CopyEdit
Student(); // No args
Student(char* name); // One arg
Student(char* name, int rollNo);// Two args
Student(int rollNo, char* name, float GPA); // Three args
08.8 Using Default Parameter Values
One constructor can act like many using default values.
cpp
CopyEdit
Student(char* name = NULL, int rollNo = 0, float GPA = 0.0);
08.9 Copy Constructor
Called when:
1. Object is initialized from another.
2. Passed by value to function.
Compiler provides a default, but you can override.
cpp
CopyEdit
Student(const Student &obj) {
rollNo = obj.rollNo;
}
08.10 Shallow Copy
Default copy constructor copies pointer addresses (not data).
Causes problems if dynamic memory is used (e.g., char* name).
08.11 Deep Copy
Allocates new memory and copies content, not just pointer.
cpp
CopyEdit
Student::Student(const Student &obj) {
name = new char[strlen(obj.name) + 1];
strcpy(name, obj.name);
}
✅ Key Terms to Remember
Term Meaning
Member Function Operates on class data
Inline Function Speeds up execution by avoiding function calls
Constructor Initializes objects
Default Constructor No parameters
Copy Constructor Copies object data
Shallow Copy Copies pointers (dangerous with dynamic memory)
Deep Copy Allocates new memory and copies values
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Lecture 09 Summary – Copy Constructor & Related Concepts
✅ 1. Copy Constructor
Purpose: Creates a new object as a copy of an existing object.
Called when:
o Object is initialized with another (e.g., Student B = A;)
o Object is passed by value to a function
🔧 Syntax:
cpp
CopyEdit
Student::Student(const Student &obj) {
rollNo = obj.rollNo;
name = obj.name;
GPA = obj.GPA;
}
✅ 2. Shallow Copy
Default behavior of compiler-generated copy constructor.
Simply copies data member values.
Problem: With dynamic memory, it causes dangling pointers because both objects point
to the same memory.
❌ Dangling Pointer Issue Example:
cpp
CopyEdit
Student studentA("Ahmad", 1);
Student studentB = studentA; // shallow copy
Deleting one affects the other as both share memory.
✅ 3. Deep Copy
Custom copy constructor that allocates separate memory and copies values.
Avoids dangling pointer issues.
🔧 Syntax:
cpp
CopyEdit
Student::Student(const Student &obj) {
name = new char[strlen(obj.name)+1];
strcpy(name, obj.name);
rollNo = obj.rollNo;
}
✅ 4. Destructor
Purpose: Frees dynamically allocated memory.
Syntax: Same name as class, preceded with ~
Example:
cpp
CopyEdit
~Student() {
delete []name;
}
Order of Execution:
o Constructor: Called in object declaration order.
o Destructor: Called in reverse order.
✅ 5. Accessor Functions
Also called getters and setters.
Used to access and modify private data safely.
Setter Example:
cpp
CopyEdit
void setRollNo(int aRollNo) {
if(aRollNo < 0) rollNo = 0;
else rollNo = aRollNo;
}
Getter Example:
cpp
CopyEdit
int getRollNo() {
return rollNo;
}
✅ 6. this Pointer
Points to the calling object inside a member function.
Automatically passed to non-static member functions.
Internally: Function with n parameters becomes n+1 with this.
🔍 Key Points
1. Default copy constructor is fine for non-dynamic data.
2. For dynamic memory, always implement a custom copy constructor (deep copy).
3. Destructors prevent memory leaks.
4. Never return data member references in getters.
5. Use this pointer to resolve naming conflicts and access the current object
📘 Lecture 10 Summary – CS304
🔹 10.1 this Pointer
this is an implicit pointer available inside all non-static member functions.
It points to the current object calling the function.
Commonly used when returning the current object from a function using:
cpp
CopyEdit
return *this;
Example (method chaining):
cpp
CopyEdit
bStudent = aStudent.setName("Ali").setRollNo(2);
🔹 10.2 Separation of Interface and Implementation
Interface = Public member functions (what user sees/uses).
Implementation = Actual code (how it works internally).
Helps in modifying internal code without changing external usage.
In C++, it's commonly done using:
o .h file → class declaration (interface)
o .cpp file → function definitions (implementation)
🔹 10.3 Complex Number Example
Complex numbers can be represented in two ways:
o Old (Cartesian form): x + iy
o New (Polar form): |z|(cosθ + i sinθ)
Interface (methods like setNumber, getX, getY) remains the same.
Internal implementation can change from x, y to z, θ without affecting user code.
🔹 10.4 const Member Functions
Used for read-only operations.
Declared with const at the end:
cpp
CopyEdit
int getRollNo() const;
Benefits:
o Prevents accidental data modification.
o Compiler gives error if a const function tries to change data.
o Improves code safety and reliability.
Note: Constructors and destructors cannot be const.
🔹 10.5 this Pointer in Const Functions
In normal functions:
cpp
CopyEdit
Student* const this;
In const member functions:
cpp
CopyEdit
const Student* const this;
Prevents modifying object state via this in const functions.
✅ Key Points
Use *this to return current object (for chaining).
Separate interface (header) and implementation (source) for clean code.
Use const functions for safety and to enforce read-only access.
Constructors/destructors cannot be const.
Const functions receive a const this pointer.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
✅ CS304 – Lecture 11 Summary
🔹 11.1 Constant Data Members
If a data member is declared as const, its value cannot be changed once assigned.
Example:
cpp
CopyEdit
class Student {
const int rollNo;
public:
Student(int aRollNo); // Constructor
int getRollNo();
};
Problem: Can't assign const member inside constructor body – compiler error.
🔹 11.2 Initialization vs Assignment
Term Example Meaning
Initialization int x = 5; Value given at the time of creation
Assignment x = 10; Value assigned after creation
🔹 11.3 Member Initializer List
Used to initialize const or reference members (which can’t be assigned later).
Syntax:
cpp
CopyEdit
Student(int aRollNo) : rollNo(aRollNo) { }
Order of initialization is based on declaration order in the class, not order in initializer
list.
🔹 11.4 Const Objects and Const Member Functions
Declared as:
cpp
CopyEdit
const Student obj(5);
Const objects can only access const member functions:
cpp
CopyEdit
int getRollNo() const { return rollNo; }
Use const keyword after function declaration to ensure it doesn’t modify the object.
🔹 11.5 Static Variables
Static variable in a function: Initialized once, retains value between calls.
cpp
CopyEdit
void func() {
static int count = 0;
count++;
}
Static data member in class:
o Shared among all objects.
o Syntax:
cpp
CopyEdit
class Student {
static int noOfStudents;
};
int Student::noOfStudents = 0; // Initialization outside the class
🧠 Key Takeaways
Use member initializer list to assign values to const data members.
Const functions are needed for const objects.
Static members are shared among all class objects and are not part of any specific
object.
📘 Lecture 11 – Urdu Summary
🔹 Constant Data Member ()کونسنٹ ڈیٹا ممبر
اگر کسی ڈیٹا ممبر کوconst قرار دیں تو اس کی ویلیو بعد میں تبدیل نہیں ہو سکتی۔
جیس:
cpp
CopyEdit
const int rollNo;
اس کوinitialize کرنے کے لیےconstructor کے اندرassignment نہیں ہو سکتی۔
ح ل: Member Initializer List استعمال کریں:
cpp
CopyEdit
Student(int r) : rollNo(r) { }
🔹 Initialization vs Assignment فرق
Initialization = ویلیو بنانے کے وقت دیں:
cpp
CopyEdit
int x = 10;
Assignment = بعد میں ویلیو دیں:
cpp
CopyEdit
int x;
x = 10;
🔹 Member Initializer List
const اورreference ڈیٹا ممبرز کوinitialize کرن کا طریق
Constructor کے بعدcolon : لگا کرinitialize کیا جاتا ہے۔
🔹 Const Objects اورConst Functions
const objects صرفconst member functions کو کال کر سکتے ہیں۔
Function کوconst بنانے کاsyntax:
cpp
CopyEdit
int getRollNo() const;
🔹 Static Variables
Static variable کیlifetime پوریprogram life تک رہتی ہے۔
وہ تمامobjects میں شیئر ہوتے ہیں۔
Initialize کرنے کاsyntax:
cpp
CopyEdit
static int count;
اورclass کے باہر:
cpp
CopyEdit
int Student::count = 0;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Lecture 12 Summary
📘 Lecture 12 – Urdu Summary
🔹 Static Data Member کیا ہوتا ہے؟
وہdata member جو تمامobjects میںshare ہوتا ہے۔
object کے بجائےclass کیmemory میںstore ہوتا ہے۔
🔹 Static Member کاSyntax:
cpp
CopyEdit
class Student {
static int noOfStudents;
};
int Student::noOfStudents = 0;
🔹 Instance vs Static Members:
Instance Variable Static Variable
ہرobject تمام کے لیے الگobjects میں مشترک
object کے ساتھ
object کے بغیر بھی زندہ رہتا ہے
destroy
🔹 Access کرنا:
Object س: objectName.variableName
Class س: ClassName::variableName
cpp
CopyEdit
Student s1;
s1.noOfStudents = 1;
Student::noOfStudents = 1;
🔹 Life of Static Members:
Object کے بننے سے پہلے بھیstatic member memory میں ہوتا ہے۔
Object ختم ہونے کے بعد بھی باقی رہتا ہے۔
🔹 Use Case:
Number of Students Track کرنا
cpp
CopyEdit
class Student {
static int noOfStudents;
public:
Student() { noOfStudents++; }
~Student() { noOfStudents--; }
};
int Student::noOfStudents = 0;
🔹 Static Member Function:
وہfunction جوobject ک بغیرcall ہو سکتا ہے۔
صرفstatic data members access کر سکتا ہے۔
cpp
CopyEdit
class Student {
static int noOfStudents;
public:
static int getTotalStudents() {
return noOfStudents;
}
};
❌ Static member function this pointer اس لیے، نہیں رکھتاnon-static members access نہیں کر سکتا۔
🔹 Global Variable vs Static Member:
Global Variable Static Member
صرفclass کے اندر
پورےprogram میںaccessible
access
bad practice better design
🔹 Array of Objects:
Array of objects بنانے کے لیےdefault constructor ضروری ہے۔
cpp
CopyEdit
class Test {
public:
Test() { }
};
Test t[2]; // OK
// اگرparameter واالconstructor و:
class Test {
public:
Test(int x);
};
Test t[2]; // ❌ Error
Test t[2] = {Test(1), Test(2)}; // ✅
Lecture 12 Summary – Static Members and Functions
Static Data Member
A static data member is part of a class but not part of any object.
It is shared by all instances (objects) of the class.
Memory for static members is allocated in the class space, not per object.
Syntax
cpp
CopyEdit
class Student {
static int noOfStudents;
};
int Student::noOfStudents = 0; // Definition and initialization outside class
Instance Variable vs Static Variable
Instance Variable Static Variable
Each object has its own copy Shared among all objects
Stored separately per object Stored once in class memory
Accessing Static Data Member
Through object: objectName.staticMember
Through class: ClassName::staticMember
cpp
CopyEdit
Student s1;
s1.noOfStudents = 1; // Access via object
Student::noOfStudents = 1; // Access via class name
Life of Static Data Members
Created even if no objects exist.
Remain in memory after objects are destroyed.
Use Case Example
Tracking the total number of Student objects created:
cpp
CopyEdit
class Student {
static int noOfStudents;
public:
Student() { noOfStudents++; }
~Student() { noOfStudents--; }
}
;
int Student::noOfStudents = 0;
Static Member Function
Functions that can be called without an object.
Used to access static data members.
Cannot access non-static members or use the this pointer.
cpp
CopyEdit
class Student {
static int noOfStudents;
public:
static int getTotalStudents() {
return noOfStudents;
};
this Pointer and Static Functions
this pointer is passed implicitly to non-static member functions.
Static member functions do NOT receive a this pointer because they do not act on any
specific object.
Global Variable vs Static Member
Global Variable Static Member
Accessible globally in program Accessible only inside class
Violates information hiding Better encapsulation
Array of Objects
To create an array of objects, a default constructor must be present.
If only parameterized constructors exist, array initialization needs explicit object
initialization.
cpp
CopyEdit
class Test {
public:
Test() { }
};
Test arr[2]; // OK
class Test {
public:
Test(int x);
};
Test arr[2]; // Error: no default constructor
Test arr[2] = { Test(1), Test(2) }; // OK
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Here is the summary of Lecture 13 with all key points covered and short, clean code snippets
for each major concept:
🔹 13.1. Pointer to Objects
Concepts:
Pointer to objects behaves like pointers to built-in types.
You can use them to access members and allocate objects dynamically.
🔸 Code Example 1: Pointer to Object
Student obj;
Student *ptr = &obj;
ptr->setRollNo(10); // Using arrow operator to access method
🔸 Code Example 2: Using new Operator
Student *ptr = new Student();
ptr->setRollNo(10);
🔸 Code Example 3: Passing Parameter to Constructor
Student *ptr = new Student("Ali");
ptr->setRollNo(10);
🔸 Code Example 4: Creating Array of Objects
Student *ptr = new Student[100];
for(int i = 0; i < 100; i++) {
ptr[i].setRollNo(10); // Use array index for each object
}
🔹 13.2. Breakup of new Operator
Step 1: Allocates memory.
Step 2: Calls the constructor to initialize object.
🔹 13.3. Case Study: Date Class
Operations Needed:
Set/get day, month, year
Add days/months/years
Set default date
🔸 Attributes:
class Date {
int day, month, year;
static Date defaultDate; // shared by all objects
};
🔸 Interfaces:
void setDay(int);
int getDay() const;
void addYear(int);
static void setDefaultDate(int, int, int); // static function
🔹 Constructor & Destructor
🔸 Constructor Example:
Date::Date(int d, int m, int y) {
day = (d == 0) ? defaultDate.day : d;
month = (m == 0) ? defaultDate.month : m;
year = (y == 0) ? defaultDate.year : y;
}
🔸 Destructor:
Date::~Date() {
cout << "Date Destructor\n";
}
🔹 Member Functions
🔸 Setters and Getters:
void Date::setDay(int d) { day = d; }
int Date::getDay() const { return day; }
void Date::setMonth(int m) {
if(m > 0 && m <= 12) month = m;
}
int Date::getMonth() const { return month; }
void Date::setYear(int y) { year = y; }
int Date::getYear() const { return year; }
🔸 Add Year:
void Date::addYear(int x) {
year += x;
if(day == 29 && month == 2 && !leapYear(year)) {
day = 1; month = 3;
}
}
🔸 Leap Year Check:
bool Date::leapYear(int x) const {
return (x % 4 == 0 && x % 100 != 0) || (x % 400 == 0);
}
🔸 Static Default Date Setter:
void Date::setDefaultDate(int d, int m, int y) {
if(d >= 0 && d <= 31) defaultDate.day = d;
// Similar checks for m and y
}
🔹 Main Function Example
int main() {
Date aDate(0, 0, 0);
aDate.setDate(20, 10, 2011);
return 0;
}
✅ Key Concepts (Flashcards Style)
Concept Description
Pointer to Object Points to object and accesses members using ->
Concept Description
new Operator Dynamically creates object & calls constructor
Static Member Shared by all instances of class
Constructor Initializes members, runs on object creation
Destructor Cleans up, runs when object is destroyed
Composition Using objects inside other objects
leapYear() Helper function to check for leap year
Setter/Getter Modify and access private members
Array of Objects Use new Class[n] and access via indexing
Let me know if you'd like flashcards or MCQs from this lecture.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
🎓 CS304 - Lecture 14 Summary (Composition) | Urdu + Hinglish Explanation
📌 Introduction to Composition
Composition ek "has-a" relationship hota hai jahan ek object doosray object ka part hota hai.
Agar aik object dusray ka essential part hai aur uski zindagi (lifetime) doosray object par depend
karti hai to isay composition kehtay hain.
Example:
Person has hands, eyes → part of a whole
Student has a name → “has-a” relationship
🧑🎓 Student Class – Old Version (with char*)
cpp
CopyEdit
class Student {
private:
float gpa;
char *name;
int rollNumber;
public:
Student(char * = NULL, int = 0, float = 0.0);
Student(const Student &);
const char *GetName() const;
~Student();
};
🔸 Issues with Raw Pointers (char*)
name ke liye dynamically memory allocate karte hain using new.
Copy constructor mein deep copy required.
Destructor mein delete[] name; zaroori hai warna memory leak ho sakti hai.
Reusability aur safety mein problems hoti hain.
🔄 Improved Version Using Composition (with String Class)
New Student class uses an object of String class instead of char*
cpp
CopyEdit
class Student {
private:
float gpa;
int rollNumber;
String name; // composition: String is part of Student
public:
Student(char* =NULL, int=0,float=0.0);
Student(const Student &);
void SetName(const char *);
String GetName() const;
const char *GetNamePtr() const;
~Student();
};
✅ Advantages:
Deep copy, memory management, dynamic allocation sab String class mein shift ho
gaya.
Code simpler and modular ho gaya.
Memory leak ka masla khatam ho gaya.
📦 String Class (Composed Class)
cpp
CopyEdit
class String {
private:
char *ptr;
public:
String(); // default constructor
String(const String &); // copy constructor
void SetString(const char *);
const char *GetString() const;
~String();
};
🔧 SetString():
Pehle old memory delete hoti hai, phir new memory allocate hoti hai.
Ensures no memory leakage or dangling pointers.
🧪 Constructor/Destructor Flow in Composition
cpp
CopyEdit
Student *aStudent = new Student("Fakhir", 899, 3.1);
🔹 Output:
vbnet
CopyEdit
Constructor::String..
Constructor::Student..
Name: Fakhir
Destructor::Student..
Destructor::String..
🔁 Order of Execution:
Constructor: Pehle String ka constructor call hota hai, phir Student ka.
Destructor: Pehle Student ka destructor call hota hai, phir String ka.
Yeh is liye hota hai kyunki Student ne String ko apne andar include kiya hua hai.
🧠 Important Concepts Explained
1. Composition = “has-a” relationship
o Student has a name (String)
o Bird has a beak
2. Accessing Composed Object’s Function:
cpp
CopyEdit
name.SetString(s.name.GetString());
3. Memory Handling:
o Pehle memory delete karo → fir new memory assign karo
oPrevents memory leakage and shared memory bugs
4. Encapsulation:
o String class internally manages char* ptr
o Student doesn't need to manage char* directly
5. Code Reusability:
o C++ promotes reusing code by creating reusable classes (String in this case)
📘 Key Concepts / Flashcards
Concept Explanation
Composition A “has-a” relationship between objects
Deep Copy Copying content instead of just memory address
Destructor Order Composing object (Student) is destroyed before composed object (String)
Constructor Order Composed object (String) is created before composing object (Student)
String Class Manages dynamic memory of char* safely
SetString() Handles previous memory cleanup before assigning new string
GetNamePtr() Returns internal string pointer safely using const
Encapsulation Implementation details (memory allocation) hidden inside String class
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Lecture No. 15
🔹 1. Composition in C++
Definition: Jab ek class ka object dusri class ke object ko as a data member use karta hai, usay
composition kehtay hain.
Yeh strong relationship hoti hai — sub-object ka life cycle parent object ke sath tied hota hai.
👨🎓 Example: Student class with String class
cpp
CopyEdit
class Student {
float gpa;
int rollNumber;
String name; // composed object
};
✅ Constructor Using SetString()
cpp
CopyEdit
Student::Student(char *n, int roll, float g){
name.SetString(n); // Must call explicitly
rollNumber = roll;
gpa = g;
}
❌ Issue: Har baar SetString() manually call karna padta hai.
🔹 2. Overloaded Constructor in Composed Class
To solve the issue, hum String class ka overloaded constructor banate hain:
cpp
CopyEdit
String::String(char *str){
if(str != NULL){
ptr = new char[strlen(str)+1];
strcpy(ptr, str);
} else {
ptr = NULL;
}
cout << "Overloaded Constructor::String..\n";
}
✅ Member Initialization List (Preferred Way)
cpp
CopyEdit
Student::Student(char *n, int roll, float g) : name(n) {
rollNumber = roll;
gpa = g;
}
🎯 Is approach se name(n) line string object ko directly initialize kar deti hai.
🔹 3. Composition with Multiple Classes
Now Student class includes Date object too:
cpp
CopyEdit
class Student {
Date birthDate;
String name;
...
};
Student::Student(char *n, const Date &d, int roll, float g)
: name(n), birthDate(d) { ... }
✅ Output:
rust
CopyEdit
Overloaded Constructor::Date..
Copy Constructor::Date..
Overloaded Constructor::String..
Constructor::Student..
📸 Overloaded vs. Non-overloaded Constructor (Diagram)
Constructor Type Usage
Non-Overloaded String()
Overloaded String(char *str)
📷 Diagram representation (Add a diagram showing both constructor types with arrows pointing
to usage in Student class)
🔹 4. Aggregation
Definition: Weak relationship hai — objects independent hote hain lekin ek dusre ki services use
karte hain.
📘 Examples:
Student ↔ Teacher
Passenger ↔ Bus
Room ↔ Chair
💡 Difference with Composition:
Composition Aggregation
Part-of relationship Uses relationship
Object contained in class Pointer/reference used
Lifespan tied to parent Lifespan can be independent
🪑 Example: Room and Chairs
cpp
CopyEdit
class Room {
Chair* chairs[50]; // aggregation using pointers
...
};
⚙️Room Methods:
cpp
CopyEdit
void AddChair(Chair *c, int chairNo) {
chairs[chairNo] = c;
}
bool FoldChair(int chairNo) {
return chairs[chairNo]->FoldChair();
}
✅ Main Function:
cpp
CopyEdit
Chair ch1;
{
Room r1;
r1.AddChair(&ch1, 1);
r1.FoldChair(1);
}
ch1.UnFoldChair(); // still accessible, independent of Room
🔹 5. Friend Functions
Definition: Aisi functions jo kisi class ke private members ko access kar sakti hain bina us class
ka member bane.
❓ Why Needed?
Reusability across multiple classes
Allows global functions to access private members
⚠️OOP Violation?
Yes, friend functions break encapsulation because they bypass class boundaries.
💡 Example:
cpp
CopyEdit
class X {
int a, b;
friend void DoSomething(X);
};
void DoSomething(X obj) {
obj.a = 3;
obj.b = 4;
}
✅ Rules:
Declare friend inside class
Do NOT use friend in function definition
Friend functions are not member functions
🔹 6. Friend Class
One class can also access private data of another using friend class.
cpp
CopyEdit
class X {
friend class Y;
int x_var1;
};
class Y {
X objX;
void setX() {
objX.x_var1 = 1; // Allowed
}
};
🔑 Key Concepts (Flashcards Style)
🔑 Term 💡 Explanation
Composition Strong relation, object contained inside class, lifetime tied
Aggregation Weak relation, uses pointer/reference, objects can live independently
Overloaded Constructor Constructor with parameters
Member Initialization List Preferred method to initialize composed objects
Friend Function Non-member function accessing private data
Friend Class Entire class can access private data of another
Encapsulation Violation Friend functions bypass access restrictions
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
📘 Lecture No. 16 Summary – Operator Overloading
🔹 16.1 Operator Overloading (Motivation)
Given Class:
cpp
CopyEdit
class Complex {
private:
double real, img;
public:
Complex Add(const Complex &);
Complex Subtract(const Complex &);
Complex Multiply(const Complex &);
};
Addition Example:
cpp
CopyEdit
Complex Complex::Add(const Complex & c1){
Complex t;
t.real = real + c1.real;
t.img = img + c1.img;
return t;
}
Usage:
cpp
CopyEdit
Complex c3 = c1.Add(c2); // two operations:
1. c1.Add(c2) → calls function, returns temporary object.
2. c3 = tempObj → copy constructor called.
🔸 Problems Without Operator Overloading
1. Inconvenience:
o You cannot write c1 + c2; like basic types.
o You must know function details (Add) to use them.
2. Chained Expressions Are Hard:
cpp
CopyEdit
c1 + c2 + c3 + c4; // ❌ Not possible
Must write:
cpp
CopyEdit
c1.Add(c2.Add(c3.Add(c4))); // ❌ Complex and unreadable
OR:
cpp
CopyEdit
t1 = c3.Add(c4);
t2 = c2.Add(t1);
t3 = c1.Add(t2);
✅ Solution: Operator Overloading
You can redefine operators like +, -, * for user-defined types (classes).
Works just like with built-in types (int, float, etc).
Makes code readable, simpler, and maintainable.
Example:
cpp
CopyEdit
Complex c3 = c1 + c2 + c3;
🖼️Overloadable vs Non-Overloadable Operators
✅ Can Be Overloaded ❌ Cannot Be Overloaded
+, -, *, /, %, =, ==, !=, <, > . (dot)
<=, >=, [], (), ->, ++, -- .* (pointer to member)
<<, >>, &=, =, ^=, +=, -=
*=, /=, %=, <<=, >>= ?: (ternary conditional)
new, delete, new[], delete[] sizeof, typeid
🔹 Example of Built-in Overloading
cpp
CopyEdit
float x;
int y;
x = 102.02 + 0.09; // calls float addition
y = 50 + 47; // calls int addition
C++ internally uses:
cpp
CopyEdit
Add(int a, int b);
Add(float a, float b);
🔹 Precedence & Associativity
Precedence of operators does not change after overloading.
Associativity also remains the same.
Examples:
cpp
CopyEdit
c1 * c2 + c3; // * evaluated before +
c1 + c2 + c3; // evaluated left to right: (c1 + c2) + c3
🔹 Syntax of Operator Overloading
🔸 As a Member Function:
cpp
CopyEdit
return_type class_name::operatorOP(parameters) {
// code
}
🔸 As a Non-Member (Friend) Function:
cpp
CopyEdit
return_type operatorOP(parameters) {
// code
}
Example:
cpp
CopyEdit
Complex& Complex::operator+(const Complex & c);
OR
cpp
CopyEdit
Complex operator+(const Complex & c1, const Complex & c2);
🔹 Binary Operator Overloading
General Syntax:
Member Function:
cpp
CopyEdit
TYPE class_name::operatorOP(TYPE rhs) { /*code*/ }
Non-Member Function:
cpp
CopyEdit
TYPE operatorOP(TYPE lhs, TYPE rhs) { /*code*/ }
🔸 At least one operand must be user-defined type:
cpp
CopyEdit
int operator+(int, int); // ❌ Not allowed
🔹 Example: Overloading + Operator
cpp
CopyEdit
class Complex {
private:
double real, img;
public:
Complex operator+(const Complex & rhs);
};
Complex Complex::operator+(const Complex & rhs){
Complex t;
t.real = real + rhs.real;
t.img = img + rhs.img;
return t;
}
Usage:
cpp
CopyEdit
Complex t = c1 + c2 + c3;
// Compiler internally converts:
(c1.operator+(c2)).operator+(c3);
❌ Void Return Type Drawbacks
cpp
CopyEdit
void Complex::operator+(const Complex & rhs);
Cannot write: Complex c3 = c1 + c2 + c3;
Result stored in one existing object (e.g., c1)
No chaining of expressions
Less readable
Hard to debug and maintain
✅ Key Concepts Recap
Concept Explanation
Allows using operators (like +, -, *, etc.) with user-defined
Operator Overloading
types (classes)
Binary Operator Works on two operands (e.g., a + b)
Special function with keyword operator followed by symbol
Operator Function
(e.g., operator+)
Order of operator evaluation; remains unchanged after
Precedence
overloading
Direction of operation evaluation (left-to-right or right-to-left);
Associativity
also unchanged
Overloadable Operators Most common operators like +, -, *, =, [], () etc.
Non-Overloadable Operators ., ::, ?:, sizeof, typeid, .*
Prevents chaining like a + b + c, result must be stored in one
Void Return Type Issue
of the operands
Syntax for Overloading Can be member function or friend (non-member) function
User-Defined Operand At least one operand must be of user-defined type in
Requirement overloading
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Lecture 17 Summary – Binary Operators (cont.) &
Assignment Operator Overloading
🔄 Binary Operator Behavior in C++
Binary operator (like +) is always called on the left-hand operand.
Examples:
cpp
CopyEdit
c1 + c2 → c1.operator+(c2)
c2 + c1 → c2.operator+(c1)
➕ Adding Basic Data Type (e.g., double) to Complex Class
Problem:
You can add two Complex objects but not a Complex object with a double:
cpp
CopyEdit
Complex c1;
c1 + 2.325; // ❌ error
Solution:
Overload + for both Complex + double and double + Complex.
✅ Modified Complex Class:
cpp
CopyEdit
class Complex {
...
Complex operator+(const Complex &rhs); // Complex + Complex
Complex operator+(const double &rhs); // Complex + double
friend Complex operator+(const double &lhs, const Complex &rhs); // double
+ Complex
};
Implementations:
cpp
CopyEdit
// Complex + double
Complex Complex::operator+(const double &rhs) {
Complex t;
t.real = real + rhs;
t.img = img;
return t;
}
// double + Complex
Complex operator+(const double &lhs, const Complex &rhs) {
Complex t;
t.real = lhs + rhs.real;
t.img = rhs.img;
return t;
}
🧠 Why friend?
friend functions are non-member functions.
Needed when the left operand is not an object of the class (e.g., 450.12 + c1).
✅ Final Complex Class Operator Overloads:
cpp
CopyEdit
class Complex {
...
Complex operator+(const Complex &);
Complex operator+(const double &);
friend Complex operator+(const Complex &, const double &);
friend Complex operator+(const double &, const Complex &);
};
🔄 Other Binary Operators
Overloading is similar for:
cpp
CopyEdit
Complex operator*(const Complex &c1, const Complex &c2);
Complex operator/(const Complex &c1, const Complex &c2);
Complex operator-(const Complex &c1, const Complex &c2);
📥 Overloading the Assignment Operator (=)
📌 Compiler provides these by default:
1. Default Constructor
2. Copy Constructor
3. Assignment Operator
But these default versions do a shallow copy, which causes:
Dangling pointers
Memory leaks (especially with dynamic memory)
💡 Why Overload Assignment Operator?
When your class uses dynamic memory, default assignment creates problems:
cpp
CopyEdit
String str1("Hello");
String str2("World");
str1 = str2; // Shallow copy: old memory not deleted → leak
🛠️Correct Assignment Operator (Deep Copy):
cpp
CopyEdit
class String {
int size;
char *bufferPtr;
public:
String &operator=(const String &rhs); // Return by reference
};
String &String::operator=(const String &rhs) {
size = rhs.size;
delete[] bufferPtr; // Free old memory
if (rhs.size != 0) {
bufferPtr = new char[size + 1];
strcpy(bufferPtr, rhs.bufferPtr); // Deep copy
} else {
bufferPtr = NULL;
}
return *this; // To allow chaining: str1 = str2 = str3;
}
🔁 Chained Assignment Problem:
cpp
CopyEdit
str1 = str2 = str3;
Resolved as:
cpp
CopyEdit
str1.operator=(str2.operator=(str3))
This fails if assignment operator returns void.
✅ Solution: Return *this by reference to allow chaining.
✅ Key Takeaways
Overload + to work with both Complex + double and double + Complex.
Use friend functions for double + Complex (non-member function required).
Always overload assignment operator (=) in classes with dynamic memory.
Return reference from assignment operator for chained assignments.