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:

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.

Main.cpp
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.

Main.cpp
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

Step-by-Step Process

  1. Define the class with private attributes.
  2. Implement the constructor.
  3. Write the methods with range checks (e.g., brightness between 0-100).
  4. In main(), create lights for "Bedroom" and "Kitchen" and control them.

Expected Deliverables

Solve in Compiler