Object Oriented ProgrammingUnit 28 min read
Classes and Objects: Structure, Access, and Real-World Modeling
Unit 2 of Object Oriented Programming covers the core concepts of classes (blueprints) and objects (instances), including data members, member functions, access specifiers (public, private, protected), constructors/destructors, and object interaction. This note explains how to design classes, access members, and use ob
Core Concepts: Classes and Objects
1. What is a Class?
A class is a blueprint or template that defines the structure (data members) and behavior (member functions) of objects. It encapsulates data and functions into a single unit.
Example:
classDiagram
class Car {
-string model
-int year
+void display()
+void setModel(string m)
}
class Person {
-string name
-Car car
+void buyCar(Car c)
}
Person --> Car : owns- Data Members (Attributes): Variables that store data (e.g.,
model,year). - Member Functions (Methods): Functions that operate on data (e.g.,
display(),setModel()).
Why Classes?
- Modularity: Group related data and functions.
- Reusability: Create multiple objects from one class.
- Data Hiding: Protect sensitive data using
privateaccess.
2. What is an Object?
An object is an instance of a class. It occupies memory and holds actual values.
Example:
#include <iostream>
using namespace std;
class Student {
public:
string name;
int roll;
void display() {
cout << "Name: " << name << ", Roll: " << roll << endl;
}
};
int main() {
Student s1; // Object creation
s1.name = "Ramesh";
s1.roll = 101;
s1.display();
return 0;
}
Output:
Name: Ramesh, Roll: 101
Visualization of Object Creation:
flowchart TD
A["Class: Student"] -->|"Blueprint"| B["Object: s1"]
B --> C["Memory Allocation\n(name: \"Ramesh\", roll: 101)"]3. Access Specifiers: Public, Private, Protected
Access specifiers control how members of a class can be accessed.
| Specifier | Access Level | Usage Example |
|---|---|---|
public |
Accessible everywhere | public: int age; |
private |
Accessible only within the class | private: string password; |
protected |
Accessible within class and derived classes | protected: int salary; |
Example:
class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
balance += amount;
}
void displayBalance() {
cout << "Balance: " << balance << endl;
}
};
Why private?
- Prevents unauthorized modification of data (e.g.,
balancein a bank account).
4. Member Functions
Functions defined inside a class to perform operations on its data.
Types of Member Functions:
- Instance Member Functions: Operate on object data (e.g.,
display()). - Static Member Functions: Belong to the class, not objects (e.g.,
getCount()). - Friend Functions: Non-member functions with access to private members.
Example: Static Member Function
class Counter {
private:
static int count;
public:
Counter() { count++; }
static int getCount() { return count; }
};
int Counter::count = 0;
int main() {
Counter c1, c2;
cout << "Objects created: " << Counter::getCount(); // Output: 2
}
5. Constructors and Destructors
Constructors
- Special member functions called when an object is created.
- Used to initialize objects.
Types:
- Default Constructor: No arguments.
- Parameterized Constructor: Takes arguments.
- Copy Constructor: Initializes using another object.
Example:
class Rectangle {
private:
int width, height;
public:
Rectangle(int w, int h) { width = w; height = h; } // Parameterized
int area() { return width * height; }
};
int main() {
Rectangle r1(10, 5); // Constructor called
cout << "Area: " << r1.area(); // Output: 50
}
Visualization of Constructor Execution:
flowchart TD
A["Rectangle r1(10, 5);"] --> B["Memory Allocated\nwidth=10, height=5"]
B --> C["Constructor Called\nInitializes width & height"]Destructors
- Called when an object is destroyed.
- Used for cleanup (e.g., releasing memory).
Example:
class FileHandler {
public:
~FileHandler() { cout << "File closed." << endl; }
};
int main() {
FileHandler f;
// Destructor called when 'f' goes out of scope
}
6. this Pointer
- Points to the current object.
- Used to resolve naming conflicts (e.g., member variable vs. parameter).
Example:
class Person {
private:
string name;
public:
void setName(string name) {
this->name = name; // 'this->name' refers to member, 'name' is parameter
}
};
In the Real World
eSewa (Nepal):
- Class:
User,Transaction - Objects: Each user (e.g.,
user1,user2) is an instance ofUser. - Member Functions:
payBill(),checkBalance(). - Access Specifiers:
privateforpassword,publicforuserID.
- Class:
Khalti (Digital Payments):
- Class:
Wallet - Objects: Each user’s wallet (e.g.,
wallet1,wallet2). - Constructor: Initializes balance when a new account is created.
- Destructor: Cleans up temporary session data.
- Class:
Bank Loan Calculation (Nepal):
- Class:
Loan - Data Members:
principal,interestRate,duration. - Member Function:
calculateEMI()computes monthly payments. - Example Trace:
Loan loan1(1000000, 8.5, 5); // Principal: 1M, Rate: 8.5%, Duration: 5 years cout << "EMI: " << loan1.calculateEMI(); // Output: ~19,800 NPR/month
- Class:
7. Object Interaction: Passing Objects as Arguments
Objects can be passed to functions by:
- Value: Copies the object.
- Reference: Passes the object directly (efficient for large objects).
Example: Passing by Reference
void incrementAge(Person &p) {
p.age++; // Modifies the original object
}
int main() {
Person p1;
incrementAge(p1); // p1.age increases
}
Visualization of Pass-by-Reference:
flowchart TD
A["Person p1;"] --> B["Memory Address\n&p1"]
B --> C["incrementAge(p1)"] --> D["Modifies p1.age directly"]8. Arrays of Objects
Store multiple objects of the same class in an array.
Example:
class Student {
public:
string name;
int marks;
};
int main() {
Student students[3] = {
{"Ramesh", 85},
{"Sita", 90},
{"Hari", 78}
};
for (int i = 0; i < 3; i++) {
cout << students[i].name << ": " << students[i].marks << endl;
}
}
Output:
Ramesh: 85
Sita: 90
Hari: 78
9. Dynamic Memory Allocation for Objects
Use new and delete to create objects dynamically.
Example:
class DynamicObject {
public:
int data;
DynamicObject(int d) { data = d; }
};
int main() {
DynamicObject *obj = new DynamicObject(100); // Dynamic allocation
cout << obj->data; // Output: 100
delete obj; // Free memory
}
Visualization of Dynamic Allocation:
flowchart TD
A["DynamicObject *obj = new DynamicObject(100);"] --> B["Heap Memory\nobj->data=100"]
B --> C["delete obj;"] --> D["Memory Freed"]Exam Tip
Class vs. Object:
- Class = Blueprint (e.g.,
Car). - Object = Instance (e.g.,
myCar). - Exam Question: "Define class and object with an example." → Always include both definition and a code snippet.
- Class = Blueprint (e.g.,
Access Specifiers:
privateis default in C++ (unlike Java).- Exam Question: "How are members of a class accessed?" → Explain
public,private, andprotectedwith examples.
Constructors/Destructors:
- Default constructor is called if no constructor is defined.
- Exam Question: "Write a program to create a class with a parameterized constructor." → Include initialization and object creation.
Object Interaction:
- Pass by reference is preferred for efficiency.
- Exam Question: "Write a function to compare two objects of a class." → Use member functions and return the object with lower value.
Real-World Applications:
- eSewa/Khalti: Model as classes with
privatedata (e.g.,password) andpublicfunctions (e.g.,payBill()). - Bank Loans: Use constructors to initialize loan terms and member functions to compute EMI.
- eSewa/Khalti: Model as classes with
Common Pitfalls:
- Forgetting to initialize objects (use constructors).
- Misusing
thispointer (e.g.,this->variablevs.variable). - Memory leaks (always
deletedynamically allocated objects).
Practice Questions for TU/PU Exams:
- Create a
Bookclass withtitleandprice. Write a function to return the cheaper book between two objects. - Write a program to store 5
Studentobjects in an array and display their details. - Explain the difference between pass-by-value and pass-by-reference with an example.
- Define a
BankAccountclass withdeposit()andwithdraw()methods. Useprivateforbalance.
Based on the TU BSc CSIT syllabus for Object Oriented Programming (CSC166), unit 2.
Discussion
Loading…