You will be able to
- Set up a compiler and run C++ programs
- Explain OOP, classes, objects and the four pillars
- Write classes with constructors, destructors and private data
- Split code into header and source files
How to use this page
Press Run on a code block to see its output, then type it yourself. In every live explanation press Next (or Auto play) and watch the highlighted line, the typed explanation and the memory cards change together. Finish with the practice and the quiz, then mark the module complete to decode the cipher in the sphere.
Module 1
How to start: set up C++ and run your first program
Understand what C++ is, install a compiler and compile your first file.
C++ is a general-purpose, compiled programming language created by Bjarne Stroustrup in 1979 as "C with Classes". Game engines, browsers, operating systems, embedded devices and trading systems use it because it is fast and gives you direct control over memory. C++ supports ordinary functions and also object-oriented programming (OOP), which is the subject of this whole course.
Words you will meet today
| Term | Definition | Example |
|---|---|---|
| Source code | The text you write and save in a .cpp file | main.cpp |
| Compiler | A program that translates source code into machine code the computer can run | g++, clang++, MSVC |
| Executable | The final runnable file produced by the compiler | app or app.exe |
| Editor / IDE | The tool where you type code. An IDE adds a compiler button and a debugger | VS Code, CLion, Code::Blocks |
| Header file | A file of declarations, loaded with #include | <iostream> |
| Standard library | Ready-made code that ships with C++ | string, vector, cout |
Step 1: install a compiler
| System | What to do |
|---|---|
| Windows | Install MSYS2 (msys2.org) and run pacman -S mingw-w64-ucrt-x86_64-gcc, or install Visual Studio Community and tick "Desktop development with C++". |
| macOS | Open Terminal and run xcode-select --install. |
| Linux | Ubuntu or Debian: sudo apt install g++. Fedora: sudo dnf install gcc-c++. |
Check it worked: open a terminal and run g++ --version. If you see a version number, you are ready. No install yet? An online compiler such as onlinegdb.com runs the same code in your browser.
Step 2: pick an editor
Install VS Code (free) and make a folder called cpp-oop. Every file in this course goes in that folder.
Step 3: write, compile, run
Save this as main.cpp, press Run to preview the result, then do it yourself in the terminal.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, OOP!" << endl;
return 0;
}#include <iostream> copies in the tools for input and output. using namespace std; lets you write cout instead of std::cout. int main() is where every C++ program starts. cout << ... sends text to the screen and << is the insertion operator. endl ends the line. return 0; tells the operating system the program succeeded. Every statement ends with a semicolon.Compile and run it from the terminal:
g++ -std=c++17 -Wall main.cpp -o app
./app-std=c++17 picks the language version. -Wall turns on helpful warnings. -o app names the output file. On Windows run app.exe instead of ./app.| Stage | What happens |
|---|---|
| 1. Preprocess | Lines starting with # are handled. #include pastes the header in. |
| 2. Compile | Your C++ becomes machine-code pieces called object code. |
| 3. Link | The pieces and library code are joined into one executable. |
Quick recap of C++ basics
OOP builds on variables, input and output. Read this program, then run it.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "Name: ";
cin >> name;
cout << "Age: ";
cin >> age;
cout << "Hi " << name << ", next year you will be " << age + 1 << endl;
return 0;
}string name; reserves a box for text and int age; a box for a whole number. cin >> reads what the user types into the box. age + 1 is an expression that is calculated before printing.| Type | Holds | Example |
|---|---|---|
int | Whole numbers | int age = 20; |
double | Decimal numbers | double price = 9.5; |
char | One character | char grade = 'A'; |
bool | true or false | bool ok = true; |
string | Text (needs <string>) | string city = "Pune"; |
Key takeaways
- C++ is compiled: source code goes through a compiler to make an executable
- Compile with
g++ -std=c++17 -Wall main.cpp -o app main()is the entry point of every program- A variable has a type and a name;
cinreads andcoutprints
Practice
Write a program that asks for a city and prints I live in <city> on one line and OOP is fun on the next.
Declare a string city, read it with cin, then use two cout lines with endl.
#include <iostream>
#include <string>
using namespace std;
int main() {
string city;
cout << "City: ";
cin >> city;
cout << "I live in " << city << endl;
cout << "OOP is fun" << endl;
return 0;
}Quick quiz
What does the compiler do?
The compiler turns your .cpp text into an executable the computer can run.
Which command compiles main.cpp into a program named app?
g++ is the compiler and -o app names the output file.
Module 2
What is OOP? Definitions and the four pillars
Learn the vocabulary before you write classes.
Object-oriented programming (OOP) is a way of designing programs around objects: things that bundle data (what they know) with functions (what they can do). Instead of thousands of loose variables and functions, you group them into small, self-contained pieces that model the real world: a Student, a BankAccount, a Car.
Every object has three properties:
- State: its data at this moment (a car's speed is 120).
- Behaviour: what it can do (a car can honk or brake).
- Identity: it is a separate thing, even if two objects hold the same values.
Procedural versus object-oriented
| Procedural style | Object-oriented style | |
|---|---|---|
| Main idea | A list of functions that work on data | Objects that own their data and functions |
| Data | Often shared and global | Hidden inside the object |
| Reuse | Copy and edit functions | Inheritance and composition |
| Good for | Small scripts and utilities | Large programs that keep growing |
The same idea in both styles. First the procedural version, then the OOP version you can run:
string carName = "BMW";
int carSpeed = 120;
void honk(string name) {
cout << name << " says beep!";
}
// Ten cars means twenty loose variables.#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string name;
int speed;
void honk() { cout << name << " says beep!" << endl; }
};
int main() {
Car a; a.name = "BMW"; a.speed = 120;
Car b; b.name = "Audi"; b.speed = 90;
a.honk();
b.honk();
return 0;
}name, speed) and the action (honk) live together in Car. Each object a and b carries its own data, so there is no mix-up.The four pillars of OOP
| Pillar | Definition | Real-life example | C++ tools | Level |
|---|---|---|---|---|
| Encapsulation | Bundling data with the functions that use it and hiding the details | A capsule: you take it without seeing the powder inside | class, private, getters | Beginner |
| Abstraction | Showing only what is needed and hiding how it works | A car pedal: you press it, you do not see the engine | abstract classes, virtual | Intermediate |
| Inheritance | A new class reuses and extends an existing class | A Dog is an Animal, so it inherits eat() and sleep() | class Dog : public Animal | Intermediate |
| Polymorphism | One call, many behaviours depending on the object | speak() sounds different for a Dog and a Cat | virtual, override | Intermediate |
Class versus object
| Class | Object |
|---|---|
| Blueprint or template | Real thing built from the blueprint |
| Written once in code | Created many times at run time |
| Uses no data memory by itself | Each object uses memory for its data |
| "Car" as an idea | "My red BMW" as a thing |
Key takeaways
- OOP organises code around objects that hold state and behaviour
- A class is a blueprint; an object is one real instance
- The pillars are encapsulation, abstraction, inheritance and polymorphism
- Find classes by looking for nouns and methods by looking for verbs
Practice
A library has books and members. Members borrow and return books. List the classes, their data and their methods.
Nouns: Book, Member, Library. Verbs: borrow, return, add book.
Book: title, author, isAvailable; methods markBorrowed(), markReturned().
Member: name, id, list of borrowed books; methods borrow(book), returnBook(book).
Library: list of books and members; methods addBook(), findBook(), checkout().
Quick quiz
Which pillar hides data inside a class?
Encapsulation bundles data with functions and restricts direct access.
A class is best described as…
A class describes what objects will look like. Objects are the real instances.
Module 3
Classes and objects
Define a class, create objects and use the dot operator.
Definitions
| Term | Meaning |
|---|---|
| Class | A user-defined type that groups data and functions: class Car { ... }; |
| Object (instance) | A variable whose type is a class: Car c1; |
| Data member (attribute) | A variable declared inside a class: int speed; |
| Member function (method) | A function declared inside a class: void honk() |
Dot operator . | Reaches a member of an object: c1.speed |
Arrow operator -> | Reaches a member through a pointer: p->speed |
Step through the live explanation. The dashed card is the class and the green cards are objects in memory.
A complete program
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int marks;
void show() {
cout << name << " scored " << marks << endl;
}
};
int main() {
Student s1;
s1.name = "Asha";
s1.marks = 88;
Student s2;
s2.name = "Ravi";
s2.marks = 74;
s1.show();
s2.show();
return 0;
}class Student { ... }; defines the type. public: means the members below can be used from anywhere (more in module 5). show() is a method that prints the object's own name and marks. In main, Student s1; creates the first object and the dot operator fills its data. s1.show() and s2.show() use the same code on different data.Under the hood: what happens in memory
When the program reaches Student s1; the compiler reserves one block of memory for every data member. Methods are not copied into each object: all Students share one copy of show(), and each call is told which object to work on. A million objects cost a million sets of data, not a million copies of the code. You can check an object's size with sizeof(s1).
Objects declared like Student s1; live on the stack and are destroyed automatically when their block ends. Objects made with new live on the heap and are covered in the Advanced file.
struct or class?
| struct | class | |
|---|---|---|
| Default access | public | private |
| Typical use | Plain bundles of data | Objects that protect their data |
| Everything else | Identical: both can have methods, constructors and inheritance |
Key takeaways
- A class is a blueprint, an object is a real instance
- Data members hold state, member functions give behaviour
- Use
.on objects and->on pointers to objects - Each object has its own data but all objects share the same method code
Practice
Write a Rectangle class with width and height and a method area() that returns width * height. Create two rectangles and print their areas.
The method signature is int area() and it uses return width * height;.
#include <iostream>
using namespace std;
class Rectangle {
public:
int width, height;
int area() { return width * height; }
};
int main() {
Rectangle r1; r1.width = 4; r1.height = 5;
Rectangle r2; r2.width = 3; r2.height = 3;
cout << r1.area() << " " << r2.area() << endl;
return 0;
}Quick quiz
Where is the method code stored when you create 100 objects?
Methods are shared. Only the data members are repeated per object.
What is the default access of members in a class?
In a class members are private unless you write public:. A struct defaults to public.
Module 4
Constructors and destructors
Set objects up correctly when they are born and clean up when they die.
Definitions
| Term | Meaning | Syntax |
|---|---|---|
| Constructor | A special method that runs automatically when an object is created. Same name as the class, no return type | Car() { } |
| Default constructor | Takes no arguments | Car() { speed = 0; } |
| Parameterized constructor | Takes arguments to set up the object | Car(string n, int s) |
| Initializer list | Sets members before the body runs. Preferred style | Car(string n) : name(n) { } |
| Destructor | Runs automatically when an object is destroyed. Name starts with ~, no arguments | ~Car() { } |
Step through how a constructor builds two cars:
Overloaded constructors with an initializer list
#include <iostream>
using namespace std;
class Box {
public:
int w, h;
Box() : w(1), h(1) {}
Box(int s) : w(s), h(s) {}
Box(int a, int b) : w(a), h(b) {}
void show() { cout << w << "x" << h << endl; }
};
int main() {
Box a;
Box b(5);
Box c(3, 4);
a.show();
b.show();
c.show();
return 0;
}: w(1), h(1) is an initializer list: it sets w and h directly instead of assigning inside the body. Box a; uses the default one, Box b(5) the one-argument version.Destructors
A destructor runs when an object goes out of scope, so it is the right place to close files or release memory. Objects are destroyed in the reverse order of creation. Watch it happen:
#include <iostream>
#include <string>
using namespace std;
class Demo {
public:
string id;
Demo(string s) { id = s; cout << id << " created" << endl; }
~Demo() { cout << id << " destroyed" << endl; }
};
int main() {
Demo a("A");
Demo b("B");
cout << "working" << endl;
return 0;
}main and destroyed automatically at the closing brace, last created first. You never call a destructor yourself for stack objects.Key takeaways
- A constructor has the class name and no return type; a destructor has
~and no arguments - Overload constructors to allow different ways of creating objects
- Prefer initializer lists:
Car(string n) : name(n) {} - Destructors run automatically, in reverse order of construction
Practice
Make a Book class with title and pages. Add a default constructor (title "Unknown", pages 0) and a parameterized one. Print both books.
Use an initializer list in both constructors: Book() : title("Unknown"), pages(0) {}.
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
string title;
int pages;
Book() : title("Unknown"), pages(0) {}
Book(string t, int p) : title(t), pages(p) {}
void show() { cout << title << " (" << pages << " pages)" << endl; }
};
int main() {
Book a;
Book b("C++ OOP", 320);
a.show();
b.show();
return 0;
}Quick quiz
What is the return type of a constructor?
Constructors have no return type, not even void.
Three objects a, b, c are created in that order in main. In which order are they destroyed?
Destruction is in reverse order of creation.
Module 5
Encapsulation: public, private and getters
Protect your data so only safe code can change it.
Definitions
| Term | Meaning |
|---|---|
| Encapsulation | Bundling data and the functions that use it in one class, and controlling access to the data |
| Access specifier | A keyword that sets who can use a member: public, private, protected |
| Getter (accessor) | A public method that reads a private member |
| Setter (mutator) | A public method that changes a private member after checking it |
| Invariant | A rule that must always be true, such as "balance is never negative" |
| Specifier | Who can use the member |
|---|---|
public | Any code, anywhere |
private | Only functions of the same class |
protected | The class and its derived classes (inheritance, Intermediate file) |
Watch how a private member is protected, and what the compiler says when you try to break the rule:
A safe bank account
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount(double start) { balance = start > 0 ? start : 0; }
void deposit(double amt) {
if (amt > 0) balance += amt;
}
bool withdraw(double amt) {
if (amt > 0 && amt <= balance) {
balance -= amt;
return true;
}
return false;
}
double getBalance() const { return balance; }
};
int main() {
BankAccount acc(100);
acc.deposit(50);
cout << acc.withdraw(500) << endl;
cout << acc.withdraw(30) << endl;
cout << acc.getBalance() << endl;
return 0;
}balance is private, so main cannot write acc.balance = 1000000. The constructor refuses a negative start. deposit and withdraw check the rules every time, so the invariant "balance is never negative" cannot be broken from outside. withdraw(500) returns false (printed as 0) because 500 is more than 150. withdraw(30) succeeds (1) and the balance becomes 120. The trailing const on getBalance promises it does not change the object.Key takeaways
privatedata can only be used by the class's own functions- Getters read, setters validate and then write
- Encapsulation protects invariants
- Mark read-only methods
const
Practice
Write a Student class with a private marks. Add setMarks(int) that ignores values below 0 or above 100, and getMarks(). Test both from main.
Check if (m >= 0 && m <= 100) before assigning inside setMarks.
#include <iostream>
using namespace std;
class Student {
int marks = 0;
public:
void setMarks(int m) { if (m >= 0 && m <= 100) marks = m; }
int getMarks() const { return marks; }
};
int main() {
Student s;
s.setMarks(95);
s.setMarks(250);
cout << s.getMarks() << endl;
return 0;
}Quick quiz
Why make data members private?
Private data lets you validate every change in one place.
What does a trailing const on a method mean?
double get() const promises not to change the object, and the compiler enforces it.
Module 6
Methods outside the class, the this pointer and const
Organise code like real C++ projects.
1. Define methods outside the class
Large classes become hard to read. Declare the method inside the class and write its body outside using the scope resolution operator ::, which means "this function belongs to that class". In real projects the class goes in a header (Car.h) and the bodies in Car.cpp.
#pragma once
#include <string>
class Car {
std::string name;
int speed;
public:
Car(std::string n, int s);
void honk() const;
};#pragma once stops it being included twice. Headers use std::string instead of using namespace std;.#include "Car.h"
#include <iostream>
Car::Car(std::string n, int s) : name(n), speed(s) {}
void Car::honk() const {
std::cout << name << " says beep!" << std::endl;
}Car::Car defines the constructor and Car::honk defines the method. Compile every .cpp together: g++ main.cpp Car.cpp -o app. Quotes in #include "Car.h" mean "my own header".2. The this pointer
this is a hidden pointer available inside every non-static method. It points to the object the method was called on. It resolves name clashes and lets a method return its own object so calls can be chained. Step through it:
#include <iostream>
#include <string>
using namespace std;
class Person {
string name;
public:
Person(string name) { this->name = name; }
void show() const { cout << "I am " << name << endl; }
};
int main() {
Person p("Asha");
p.show();
return 0;
}name. Inside the constructor plain name means the parameter, so this->name picks the member. It reads: "the name of this object equals the argument".3. const methods and const objects
A method marked const cannot change data members. A const object can only call const methods. Mark every getter const.
Common compile errors and how to fix them
| Compiler message | Cause | Fix |
|---|---|---|
expected ';' after class definition | Missing semicolon after the closing brace | Write }; |
'x' is private within this context | Using a private member from outside | Add a public getter or setter |
no matching function for call to 'Car::Car()' | Only a parameterized constructor exists | Pass arguments or add a default constructor |
'string' does not name a type | Missing #include <string> or std:: | Add the include and use std::string |
undefined reference to 'Car::honk()' | Method declared but .cpp not compiled or body missing | Compile every .cpp file and write the body |
passing 'const Car' as 'this' discards qualifiers | Calling a non-const method on a const object | Mark the method const |
Key takeaways
Class::methoddefines a method outside the class- Headers declare, .cpp files define; compile all .cpp files together
thispoints to the current object;*thisis the object itselfconstmethods promise not to change the object
Practice
Split a Counter class (with increment() and get() const) into Counter.h, Counter.cpp and main.cpp, then compile all three.
The header holds the class with declarations only; Counter.cpp includes the header and defines Counter::increment.
Compile with g++ -std=c++17 main.cpp Counter.cpp -o app. If you see undefined reference, you forgot to list Counter.cpp.
Quick quiz
What does this point to inside a method?
Each call gets its own this, pointing at the object used in the call.
What does Car::honk mean?
The scope resolution operator :: links a function body to its class.
REVISION · BEGINNER
Definition bank and exam-style questions
Learn each definition in one sentence. In written exams define the term first, then add a short example if asked.
Beginner C++ OOP definitions
- Object-oriented programming
- A style of programming that organises code into objects holding data and behaviour.
- Class
- A user-defined type that acts as a blueprint for objects.
- Object / instance
- A real value of a class type that occupies memory.
- Data member
- A variable declared inside a class.
- Member function / method
- A function declared inside a class that works on its objects.
- Constructor
- A special method that initialises an object when it is created.
- Destructor
- A special method that runs when an object is destroyed.
- Initializer list
- The colon list after a constructor header that initialises members directly.
- Encapsulation
- Bundling data with functions and restricting direct access to the data.
- Access specifier
- Keyword (public, private, protected) that controls who can use a member.
- this pointer
- A hidden pointer to the object on which a non-static method was called.
- Scope resolution operator
- The
::operator that names the class or namespace a name belongs to. - const method
- A method that promises not to modify the object.
- Stack
- Fast memory where local variables and objects are created and automatically destroyed.
- Header file
- A file of declarations (.h or .hpp) shared with #include.
- Compiler
- A program that translates C++ source code into machine code.
Exam-style questions with answers
Q1. What is the difference between a class and an object?
Answer: A class is a blueprint that defines data and functions. An object is a real instance of the class that occupies memory. One class can have many objects, each with its own data.
Q2. What is a constructor? Can it be overloaded?
Answer: A constructor is a special member function with the class name and no return type that runs automatically when an object is created. Yes, it can be overloaded by giving different parameter lists.
Q3. What is the difference between struct and class in C++?
Answer: Default access: struct members are public, class members are private. Everything else is the same.
Q4. When is a destructor called?
Answer: When an object goes out of scope, or when delete is used on a heap object. Local objects are destroyed in reverse order of creation.
Q5. What is encapsulation and why is it useful?
Answer: It is bundling data with the functions that operate on it and hiding the data behind public methods. It protects invariants and lets you change internals without breaking users of the class.
Q6. What is the this pointer?
Answer: A pointer to the current object, passed implicitly to non-static member functions. It is used to resolve name conflicts and to return the object for chaining.
Practical assignments
- Create a
Studentclass with private data, a constructor, getters and a validating setter. - Create a
BankAccountwith deposit, withdraw and a rule that balance never goes negative. - Split a class into a .h and a .cpp file and compile them together.
- Print a message in a constructor and destructor and predict the output order before running.
- Create an array of five objects and print each one.