Master the fundamentals of C++ with clear explanations and hands-on examples
0 / 10 topics completed
01
Introduction to C++
C++ is a powerful, high-performance programming language created by Bjarne Stroustrup in 1985 at Bell Labs.
It extends the C language with object-oriented features, making it one of the most versatile languages ever created.
C++ gives you fine-grained control over system resources and memory.
Why Learn C++?
High Performance – Used in game engines, operating systems, and browsers
Object-Oriented – Supports classes, inheritance, and polymorphism
Manual Memory Control – Pointers and direct memory management
Industry Standard – Used by Google, Microsoft, Adobe, and game studios
Foundation for DSA – The go-to language for competitive programming
Your first C++ program is the classic "Hello, World!":
Every C++ program needs a main() function — it's the entry point. The #include <iostream> directive lets you use input/output features. return 0; signals successful execution.
02
Installation & Setup
To write and run C++ code, you need a C++ compiler and a text editor or IDE.
The most common compilers are g++ (GNU Compiler Collection) and clang++.
Installing a Compiler
Linux – Install via package manager: sudo apt install g++
macOS – Install Xcode Command Line Tools: xcode-select --install
Windows – Download MinGW-w64 or use Visual Studio with the "Desktop development with C++" workload
Bash
# Verify your compiler installation
g++ --version
clang++ --version
Choosing an IDE
VS Code – Lightweight with C++ extension pack (recommended)
CLion – Full-featured C++ IDE by JetBrains
Code::Blocks – Free, beginner-friendly IDE
Bash
# Compile and run a C++ program
g++ hello.cpp -o hello # compiles to executable
./hello # runs the executable
✅
C++ is a compiled language: you write .cpp source files, compile them to a machine-executable binary with g++, and run the binary directly on your operating system.
03
Variables & Data Types
In C++, every variable must have a declared type. C++ is statically typed — once you declare a variable's type, it cannot hold a different type of value.
C++ also supports unsigned types (only non-negative values), long and short variants, and the auto keyword for type inference: auto x = 42; automatically deduces int.
Practice: Variables & Data Types
Create variables of different types and print them:
Create an int variable score with value 95
Create a double variable gpa with value 3.85
Create a string variable city with value "New York"
C++ uses cout (console output) and cin (console input) from the standard library. They are defined in the <iostream> header.
cout — Displaying Output
cout << "text" << endl; prints text followed by a newline. Use << to chain multiple values together.
C++
#include<iostream>using namespace std;
intmain() {
string name = "Alice";
int age = 25;
cout << "My name is " << name << " and I am " << age << " years old." << endl;
return0;
}
Output
My name is Alice and I am 25 years old.
cin — Reading User Input
cin >> variable reads input from the console. The extraction operator (>>) reads formatted data.
C++
#include<iostream>#include<string>using namespace std;
intmain() {
string name;
int age;
cout << "What is your name? ";
getline(cin, name);
cout << "How old are you? ";
cin >> age;
cout << "Hello, " << name << "! In 10 years you will be " << (age + 10) << "." << endl;
return0;
}
⚠️
cin >> stops at whitespace, so it won't read a full name like "John Doe". Use getline(cin, name) to read an entire line. However, after cin >>, there's often a leftover newline — use cin.ignore() before getline to clear it.
Practice: Input & Output
Write a program that asks the user for their name and favorite color, then prints a greeting.
Include <iostream> and <string>
Ask for name and favorite color using getline(cin, variable)
Print: "Hello {name}, your favorite color is {color}!"
C++
#include<iostream>#include<string>using namespace std;
intmain() {
string name, color;
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your favorite color: ";
getline(cin, color);
cout << "Hello " << name << ", your favorite color is " << color << "!" << endl;
return0;
}
05
Operators
Operators perform operations on variables and values. C++ supports arithmetic, assignment, comparison, logical, and bitwise operators.
Category
Operators
Example
Arithmetic
+ - * / %
10 + 5 → 15
Assignment
= += -= *= /= %=
x += 5
Comparison
== != < > <= >=
10 > 5 → true
Logical
&& || !
true && false → false
Increment/Decrement
++ --
i++
C++
#include<iostream>using namespace std;
intmain() {
int a = 10, b = 5;
// Arithmeticint sum = a + b;
int product = a * b;
int remainder = a % b;
// Comparison & Logicalbool isGreater = a > b;
bool bothPositive = (a > 0) && (b > 0);
cout << "Sum: " << sum << endl;
cout << "Product: " << product << endl;
cout << "Remainder: " << remainder << endl;
cout << "Is a > b? " << isGreater << endl;
cout << "Both positive? " << bothPositive << endl;
return0;
}
Output
Sum: 15
Product: 50
Remainder: 0
Is a > b? true
Both positive? true
Practice: Operators
Calculate the area and perimeter of a rectangle with width 8 and length 12.
Create int variables width and length
Calculate area = width * length
Calculate perimeter = 2 * (width + length)
Print both results using cout
C++
#include<iostream>using namespace std;
intmain() {
int width = 8;
int length = 12;
int area = width * length;
int perimeter = 2 * (width + length);
cout << "Area: " << area << endl;
cout << "Perimeter: " << perimeter << endl;
return0;
}
06
Conditional Statements
Conditionals let your program make decisions. C++ supports if, else if, else, and switch statements.
while checks the condition first; do-while runs the body at least once.
C++
#include<iostream>using namespace std;
intmain() {
// while loopint count = 0;
while (count < 5) {
cout << "While: " << count << endl;
count++;
}
// do-while loopint num = 0;
do {
cout << "Do-while: " << num << endl;
num++;
} while (num < 5);
return0;
}
⚠️
Always ensure your loop condition eventually becomes false to avoid infinite loops. Use break to exit early and continue to skip the current iteration.
Practice: Loops
Write two programs:
Use a for loop to print all even numbers from 2 to 20
Use a while loop to calculate the sum of numbers from 1 to 100
C++
#include<iostream>using namespace std;
intmain() {
// Even numbers 2-20for (int i = 2; i <= 20; i += 2) {
cout << i << endl;
}
// Sum of 1 to 100int sum = 0;
int n = 1;
while (n <= 100) {
sum += n;
n++;
}
cout << "Sum: " << sum << endl;
return0;
}
08
Functions
Functions (also called methods) are reusable blocks of code. They help you avoid repetition and organize your program into logical pieces.
C++
#include<iostream>using namespace std;
// Function with parameters and return valueintadd(int a, int b) {
return a + b;
}
// Void function (no return value)voidgreet(string name) {
cout << "Hello, " << name << "!" << endl;
}
intmain() {
int sum = add(10, 5);
cout << "Sum: " << sum << endl;
greet("Alice");
return0;
}
Output
Sum: 15
Hello, Alice!
Function Overloading
C++ allows multiple functions with the same name as long as their parameters differ (number, type, or order).
C++
#include<iostream>using namespace std;
intmultiply(int a, int b) {
return a * b;
}
doublemultiply(double a, double b) {
return a * b;
}
intmain() {
cout << multiply(5, 3) << endl; // 15
cout << multiply(2.5, 4.0) << endl; // 10return0;
}
Practice: Functions
Write a function isEven(int n) that returns true if n is even
Write a function factorial(int n) that returns the factorial of n
Create an array of 5 integers and calculate their sum using a for loop
Write code to count how many vowels are in a given string
C++
#include<iostream>#include<string>using namespace std;
intmain() {
// Sum of arrayint nums[] = {10, 20, 30, 40, 50};
int sum = 0;
for (int n : nums) {
sum += n;
}
cout << "Sum: " << sum << endl;
// Count vowelsstring str = "hello world";
int vowels = 0;
for (char c : str) {
c = tolower(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
}
}
cout << "Vowels: " << vowels << endl;
return0;
}
10
Basic Object-Oriented Programming
C++ supports Object-Oriented Programming (OOP) with classes and objects. The core principles are Encapsulation, Inheritance, and Polymorphism.
Classes & Objects
A class is a blueprint. An object is an instance with its own state and behavior.
C++
#include<iostream>#include<string>using namespace std;
// Define a classclassStudent {
public:
string name;
int age;
// ConstructorStudent(string n, int a) {
name = n;
age = a;
}
voidintroduce() {
cout << "Hi, I'm " << name << " and I'm " << age << " years old." << endl;
}
};
intmain() {
// Create objectsStudent alice("Alice", 20);
Student bob("Bob", 22);
alice.introduce();
bob.introduce();
return0;
}
Output
Hi, I'm Alice and I'm 20 years old.
Hi, I'm Bob and I'm 22 years old.
💡
Constructors have the same name as the class and no return type. The public: access specifier makes members accessible from outside the class. You can also use private: and protected: for data hiding.
Encapsulation
Bundle data and methods together, restricting direct access to fields using private with public getters/setters.
C++
#include<iostream>#include<string>using namespace std;
classPerson {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
stringgetName() { return name; }
intgetAge() { return age; }
voidsetAge(int a) {
if (a > 0) age = a;
}
};
intmain() {
Person p("Alice", 25);
cout << p.getName() << " is " << p.getAge() << endl;
return0;
}
Inheritance & Polymorphism
Create a derived class from a base class using :. Polymorphism lets derived classes override base class behavior.