Skip to main content

C++ OOP

Classes & Objects

Complete lesson for Classes & Objects using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with C++ OOP and STL where relevant.

L1

Basics — Classes & Objects

Section: C++ OOP. C++ classes and objects — blueprint vs instance, members, access, and struct vs class.

What is a class?

  • A **class** is a **blueprint / template** that defines data (properties) and functions (behaviour) for a type.
  • Declaring a class does **not** create objects by itself — it describes the shape.
  • A class is a **user-defined type** (like int is built-in, Student is yours).
  • **Real-life:** a car design blueprint, a bank account form template, a student ID card layout.
PartMeaningExample
Class nameType you inventCar, Account, Student
Data membersVariables / statebrand, speed, balance
Member functionsBehaviour / methodsstart(), deposit()
Access specifierWho can use membersprivate / public / protected

Class & object — blueprint vs instances

A class is the blueprint; an object is a live instance with its own data. The diagram covers class vs object, syntax, access specifiers, a Car example, and a bank Account real-life model.

C++ object and class infographic: class as blueprint, objects as instances, class vs object table, syntax, Car example with memory view, access specifiers, bank Account real-life example, and benefits of OOP.
C++ class & object — design the class, create powerful objects
  • Class: blueprint — data + functions; does not occupy object memory alone.
  • Object: instance — has its own data and uses memory.
  • Access: private / protected / public — default private for class.
  • struct vs class: almost same; defaults differ (public vs private).

What is an object?

  • An **object** is an **instance** of a class — a real variable created from the blueprint.
  • Each object has its **own copy** of data members (usually) and can call the class methods.
  • Objects **occupy memory**; the class definition alone does not.
  • **Real-life:** blueprint = Car class; objects = your Toyota, friend’s Honda.
  • **Real-life:** Account class → acc1 (Ravi), acc2 (Priya) with different balances.
#include <iostream>
#include <string>
using namespace std;

class Car {
private:
    string brand;
    int speed;
public:
    void setData(string b, int s) {
        brand = b;
        speed = s;
    }
    void showData() {
        cout << "Brand: " << brand << ", Speed: " << speed << " km/h\n";
    }
};

int main() {
    Car car1, car2; // two objects
    car1.setData("Toyota", 120);
    car2.setData("Honda", 100);
    car1.showData();
    car2.showData();
    return 0;
}

Differences between class and object

  • Class is design; object is the living instance.
FeatureClassObject
NatureBlueprint / templateReal instance / entity
MemoryDoes not occupy memory by itselfOccupies memory
CreationDeclared with classCreated from a class
Scope of dataCommon definition for all objectsEach object has its own data
ExampleCarcar1, car2
AnalogyHouse planBuilt houses from that plan

Differences between structure and class

  • In C++, struct and class are almost the same feature — the big default difference is **access**.
  • Style: use struct for simple data bundles; use class when you encapsulate behaviour and protect data.
Pointstructclass
Keywordstructclass
Default member access**public****private**
Default inheritance**public****private**
Can have data members?YesYes
Can have member functions?YesYes
Can have constructors/destructors?YesYes
OOP features (inheritance, etc.)?YesYes
Typical use (convention)Plain data / POD-like aggregatesEncapsulated types with invariants
From C historyC struct = data only (no methods in classic C)C++ class = OOP core idea
Example vibestruct Point { int x, y; };class Account { private: int bal; ... };
struct Point {
    int x, y; // public by default
};

class Account {
    int balance; // private by default
public:
    void deposit(int x) { balance += x; }
};

Syntax — defining a class and creating objects

  • Class ends with }; — the semicolon is required.
  • Create objects: ClassName obj;, multiple ClassName a, b;, or pointer/new.
  • Access with . on objects and -> on pointers.
class Student {
private:
    int roll;
    string name;
public:
    void set(int r, string n) { roll = r; name = n; }
    void show() { cout << roll << " " << name << "\n"; }
};

Student s;           // object
Student* p = &s;     // pointer to object
s.set(101, "Asha");
p->show();

Access specifiers

  • private — only inside the class (and friends). **Default for class.**
  • public — accessible from outside. **Default for struct.**
  • protected — class + derived classes (inheritance lesson).
  • Keep data private; expose safe public methods (encapsulation).
SpecifierInside classDerived classOutside classDefault for
privateYesNo*Noclass
protectedYesYesNo—
publicYesYesYesstruct

Data members and member functions

  • **Data members** store state; **member functions** operate on that state.
  • Define methods inside the class (implicitly inline) or outside with ClassName::method.
  • **Real-life:** Account data = balance; functions = deposit / withdraw / checkBalance.
#include <iostream>
using namespace std;

class Account {
private:
    int balance;
public:
    void setBalance(int b) { balance = b; }
    void deposit(int amt) { balance += amt; }
    void show() { cout << "Balance = " << balance << "\n"; }
};

int main() {
    Account acc;
    acc.setBalance(5000);
    acc.deposit(1500);
    acc.show();
    return 0;
}

Array of objects & objects as members

  • Student batch[50]; — many objects of the same class.
  • A class can contain another class/struct as a member (composition).
  • **Real-life:** Employee contains an Address object.
class Address {
public:
    string city;
};

class Employee {
public:
    string name;
    Address addr; // object as member
};

Why classes and objects? (benefits)

  • Model real-world entities cleanly.
  • Reuse the same blueprint for many instances.
  • Protect data (encapsulation) and organize large programs into modules.
  • Foundation for inheritance, polymorphism, and the rest of OOP.
BenefitMeaningExample
ReusabilityOne class → many objectsMany Car instances
Data protectionHide internalsprivate balance
ModularitySplit responsibilitiesCart, Payment classes
MaintenanceChange class in one placeFix withdraw logic once
Real-world modelingMap domain nounsStudent, Order, Account
L2

Advanced — Classes & Objects

Member functions outside the class

  • Declare inside; define outside with scope resolution Class::method.
  • Keeps the class body shorter — common in headers + .cpp files.
class Box {
public:
    int volume(int l, int w, int h);
};

int Box::volume(int l, int w, int h) {
    return l * w * h;
}

const member functions and encapsulation habits

  • Mark readers const: int getBalance() const; — promises not to modify the object.
  • Provide getters/setters instead of public data when rules matter (validation).
  • Prefer invariants: withdraw should not allow negative balance.
class Account {
private:
    int balance = 0;
public:
    int getBalance() const { return balance; }
    bool withdraw(int amt) {
        if (amt <= 0 || amt > balance) return false;
        balance -= amt;
        return true;
    }
};

Objects in memory — stack vs heap

  • Car c; — automatic (usually stack) lifetime until scope ends.
  • Car* p = new Car(); … delete p; — heap object (prefer smart pointers later).
  • Each object’s data members live with that object; code for methods is shared.

Separating interface and implementation

  • Put class declaration in a .h / .hpp; define members in a .cpp.
  • Include the header where objects are created — improves compile times and clarity.

Real-life class designs

  • Bank: Account with deposit/withdraw/checkBalance.
  • School: Student with roll, name, marks, showResult().
  • Shop: Product with id, price, stock, applyDiscount().
  • Game: Player with health, score, attack(), heal().
L3

Tricky Interview Points

Q1) What is a class in C++?

Answer A user-defined type that acts as a blueprint defining data members and member functions. Creating a class does not by itself allocate object memory.

Q2) What is an object?

Answer An instance of a class. Each object typically has its own copy of data members and occupies memory.

Q3) Difference between class and object?

Answer Class is the blueprint; object is a concrete instance created from that blueprint.

Q4) Differences between structure and class in C++?

Answer They are nearly identical. Default member access and default inheritance are public for struct and private for class. Conventionally struct is for data aggregates and class for encapsulated types.

Q5) What are access specifiers?

Answer private, protected, and public — they control where members can be accessed. Default for class is private; for struct is public.

Q6) How do you access members of an object?

Answer With the dot operator on objects (obj.member) and arrow on pointers (ptr->member).

Q7) Does a class occupy memory?

Answer The class definition itself does not allocate object storage. Objects created from the class occupy memory.

Q8) Can a struct have member functions in C++?

Answer Yes. In C++, struct can have methods, constructors, and other class-like features.

Q9) What is encapsulation?

Answer Bundling data and functions together and hiding internal details (usually private data + public interface).

Q10) How do you define a member function outside the class?

Answer Declare it inside the class and define it as ReturnType ClassName::functionName(...) { ... }.

Q11) Give a real-life example of class and objects.

Answer Class Account; objects acc1, acc2 for different customers with their own balances.

Q12) Why keep data members private?

Answer To protect invariants and control changes through validated methods (getters/setters), reducing misuse.

L4

Simple Programs

Car class with two objects

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

class Car {
private:
    string brand;
    int speed;
public:
    void setData(string b, int s) { brand = b; speed = s; }
    void showData() {
        cout << brand << " @ " << speed << " km/h\n";
    }
};

int main() {
    Car a, b;
    a.setData("Toyota", 120);
    b.setData("Honda", 100);
    a.showData();
    b.showData();
    return 0;
}

Student class — set and show

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

class Student {
private:
    int roll;
    string name;
public:
    void set(int r, string n) { roll = r; name = n; }
    void show() const { cout << roll << " " << name << "\n"; }
};

int main() {
    Student s;
    s.set(11, "Neha");
    s.show();
    return 0;
}

struct vs class default access

#include <iostream>
using namespace std;

struct S { int x; };      // public by default
class C { int y; public: void set(int v) { y = v; } int get() const { return y; } };

int main() {
    S s; s.x = 5;         // OK
    C c; c.set(7);        // OK via method
    cout << s.x << " " << c.get() << "\n";
    return 0;
}

Account — deposit and withdraw

#include <iostream>
using namespace std;

class Account {
private:
    int balance = 0;
public:
    void deposit(int amt) { if (amt > 0) balance += amt; }
    bool withdraw(int amt) {
        if (amt <= 0 || amt > balance) return false;
        balance -= amt;
        return true;
    }
    int getBalance() const { return balance; }
};

int main() {
    Account acc;
    acc.deposit(1000);
    acc.withdraw(250);
    cout << acc.getBalance() << "\n"; // 750
    return 0;
}

Array of objects

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

class Item {
public:
    string name;
    int qty;
    void show() const { cout << name << " x" << qty << "\n"; }
};

int main() {
    Item cart[2] = {{"Pen", 3}, {"Book", 1}};
    for (const Item& it : cart) it.show();
    return 0;
}

Method defined outside class

#include <iostream>
using namespace std;

class Box {
public:
    int volume(int l, int w, int h);
};

int Box::volume(int l, int w, int h) {
    return l * w * h;
}

int main() {
    Box b;
    cout << b.volume(2, 3, 4) << "\n"; // 24
    return 0;
}

Pointer to object

#include <iostream>
using namespace std;

class Counter {
private:
    int n = 0;
public:
    void inc() { n++; }
    int get() const { return n; }
};

int main() {
    Counter c;
    Counter* p = &c;
    p->inc();
    p->inc();
    cout << p->get() << "\n"; // 2
    return 0;
}
L5

Problem Solving Tricks

  • Class = blueprint; object = instance that uses memory.
  • Remember the trailing semicolon after a class definition.
  • Default: private in class, public in struct.
  • Keep data private; expose behaviour through public methods.
  • Use . for objects and -> for pointers to objects.
  • Name classes as nouns: Student, Order, Account.
  • Mark read-only methods const.
  • One class file pair (.h/.cpp) per significant type when projects grow.
  • struct vs class: same tools, different defaults and conventions.
  • Create many objects from one class instead of copy-pasting variables.
  • Validate in setters/withdraw — protect invariants.
  • Start simple: private data + public set/show, then grow.
L6

Practice Programs List

  1. Write a Book class with title, price; create two objects and display them.
  2. Convert a plain struct Student into a class with private data and public set/show.
  3. Make a table (on paper) of struct vs class differences; match it to the lesson.
  4. Implement Account with deposit, withdraw, getBalance; reject invalid withdraws.
  5. Create an array of 5 Product objects; print those with price > 100.
  6. Define a method outside the class using ClassName::method.
  7. Use a pointer to an object and call methods with ->.
  8. Build Employee containing an Address member object.
  9. Add a const getter to a class and call it on a const object.
  10. Design classes for a tiny library: Book, Member, Loan — list data + methods.
  11. Show that two objects of the same class do not share (non-static) data.
  12. Refactor public data fields into private with setters that validate.
  13. Write Rectangle with length/width and area()/perimeter() methods.
  14. Explain in comments class vs object using a real bank-account story.