Chapter 7 — Object-Oriented C++ (Classes & Objects)
📚 Chapter Overview
Object-Oriented Programming (OOP) is a paradigm centered around "Objects" rather than functions. In this chapter, you will learn how to build real-world models using Classes, protect data with Access Specifiers, and initialize objects using Constructors.
Learning Objectives:
- Understand the Blueprint vs Instance relationship.
- Master Public and Private access specifiers.
- Use Constructors and Destructors for memory lifecycle.
7.1 Classes and Objects
Part 1 — Definition
A Class is a template or blueprint for creating objects. It groups data and functions together. An Object is a specific instance of a class. For example, if "Car" is a class, your specific "Red Honda" is an object.
Part 2 — Syntax
class Car {
public: // Access Specifier
string brand;
void drive() { cout << "Driving..."; }
};
Car myCar; // Create Object
Part 3 — Example
Problem: Model a "Student" class and display their name.
class Student {
public:
string name;
void introduce() {
cout << "My name is " << name;
}
};
int main() {
Student s1;
s1.name = "Ali";
s1.introduce();
return 0;
}
Part 4 — Video
Video: Coming Soon
7.2 Constructors & Encapsulation
Part 1 — Definition
A Constructor is a special function that runs automatically when an object is created. Encapsulation is the practice of hiding internal data (Private) and providing public methods to access it (Getters/Setters).
Part 2 — Syntax
class Box {
private:
int size;
public:
Box(int s) { size = s; } // Constructor
};
Part 3 — Example
Problem: Protect an account balance from direct modification.
class Account {
private:
double balance;
public:
Account(double initial) { balance = initial; }
void deposit(double amt) { balance += amt; }
double getBalance() { return balance; }
};
Observation: Private data ensures that the balance cannot be set to a negative number by mistake.
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Smart Home Device" simulator using OOP.
Requirements
- Create a class
SmartLightwith attributes:roomName,isOn(bool),brightness. - Use a constructor to set the room name and turn off the light by default.
- Methods:
turnOn(),turnOff(), andsetBrightness(int val).
Step-by-Step Process
- Define the class with private attributes.
- Implement the constructor.
- Write the methods with range checks (e.g., brightness between 0-100).
- In
main(), create lights for "Bedroom" and "Kitchen" and control them.
Expected Deliverables
smart_home.cppsource file.