GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR

🏗️ Lesson 4: Classes & Objects (Intro to OOP)

⏱️ Estimated time: 35 minutes | Difficulty: Intermediate

OOP Masterclass

Objects are the building blocks of C++. A class is a blueprint, and an object is an instance of that blueprint.

What is a Class?

A class is a blueprint for creating objects. It bundles data (attributes) and functions (methods) together.

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

class Car {
public:
    string brand;
    string model;
    int year;

    // Method
    void display() {
        cout << year << " " << brand << " " << model << endl;
    }

    // Method with return value
    int getAge() {
        return 2025 - year;
    }
};

int main() {
    Car car1;
    car1.brand = "Toyota";
    car1.model = "Camry";
    car1.year = 2022;
    car1.display();  // 2022 Toyota Camry
    cout << "Age: " << car1.getAge() << endl;
    return 0;
}

Constructors

class Student {
private:
    string name;
    int age;
    double gpa;

public:
    // Constructor
    Student(string n, int a, double g) {
        name = n;
        age = a;
        gpa = g;
    }

    // Getter
    string getName() { return name; }
    double getGpa() { return gpa; }

    // Setter
    void setGpa(double g) {
        if (g >= 0 && g <= 4.0)
            gpa = g;
    }

    void display() {
        cout << name << ", Age: " << age
             << ", GPA: " << gpa << endl;
    }
};

int main() {
    Student s1("Alice", 20, 3.8);
    s1.display();
    s1.setGpa(3.9);
    return 0;
}

Access Modifiers

  • public: — Accessible from anywhere
  • private: — Only accessible inside the class
  • protected: — Accessible in the class and its subclasses

✅ Quick Quiz

❓ What is a constructor?

❓ What access modifier hides data from outside?

❓ What are getters and setters?

← Previous Next: Inheritance →