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.
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
intis built-in,Studentis yours). - **Real-life:** a car design blueprint, a bank account form template, a student ID card layout.
| Part | Meaning | Example |
|---|---|---|
| Class name | Type you invent | Car, Account, Student |
| Data members | Variables / state | brand, speed, balance |
| Member functions | Behaviour / methods | start(), deposit() |
| Access specifier | Who can use members | private / 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.
- 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.
| Feature | Class | Object |
|---|---|---|
| Nature | Blueprint / template | Real instance / entity |
| Memory | Does not occupy memory by itself | Occupies memory |
| Creation | Declared with class | Created from a class |
| Scope of data | Common definition for all objects | Each object has its own data |
| Example | Car | car1, car2 |
| Analogy | House plan | Built houses from that plan |
Differences between structure and class
- In C++,
structandclassare almost the same feature — the big default difference is **access**. - Style: use
structfor simple data bundles; useclasswhen you encapsulate behaviour and protect data.
| Point | struct | class |
|---|---|---|
| Keyword | struct | class |
| Default member access | **public** | **private** |
| Default inheritance | **public** | **private** |
| Can have data members? | Yes | Yes |
| Can have member functions? | Yes | Yes |
| Can have constructors/destructors? | Yes | Yes |
| OOP features (inheritance, etc.)? | Yes | Yes |
| Typical use (convention) | Plain data / POD-like aggregates | Encapsulated types with invariants |
| From C history | C struct = data only (no methods in classic C) | C++ class = OOP core idea |
| Example vibe | struct 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;, multipleClassName 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).
| Specifier | Inside class | Derived class | Outside class | Default for |
|---|---|---|---|---|
private | Yes | No* | No | class |
protected | Yes | Yes | No | — |
public | Yes | Yes | Yes | struct |
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:**
Employeecontains anAddressobject.
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.
| Benefit | Meaning | Example |
|---|---|---|
| Reusability | One class → many objects | Many Car instances |
| Data protection | Hide internals | private balance |
| Modularity | Split responsibilities | Cart, Payment classes |
| Maintenance | Change class in one place | Fix withdraw logic once |
| Real-world modeling | Map domain nouns | Student, Order, Account |
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 +
.cppfiles.
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:
Accountwith deposit/withdraw/checkBalance. - School:
Studentwith roll, name, marks,showResult(). - Shop:
Productwith id, price, stock,applyDiscount(). - Game:
Playerwith health, score,attack(),heal().
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.
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;
} 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.
Practice Programs List
- Write a Book class with title, price; create two objects and display them.
- Convert a plain struct Student into a class with private data and public set/show.
- Make a table (on paper) of struct vs class differences; match it to the lesson.
- Implement Account with deposit, withdraw, getBalance; reject invalid withdraws.
- Create an array of 5 Product objects; print those with price > 100.
- Define a method outside the class using ClassName::method.
- Use a pointer to an object and call methods with ->.
- Build Employee containing an Address member object.
- Add a const getter to a class and call it on a const object.
- Design classes for a tiny library: Book, Member, Loan — list data + methods.
- Show that two objects of the same class do not share (non-static) data.
- Refactor public data fields into private with setters that validate.
- Write Rectangle with length/width and area()/perimeter() methods.
- Explain in comments class vs object using a real bank-account story.