01. 🚀 C++ Basics & Program Structure
C++ is a powerful, high-performance, general-purpose programming language created by Bjarne Stroustrup in 1985 as an extension of the C programming language. Often called "C with Classes," C++ adds object-oriented programming features while maintaining C's efficiency and low-level memory manipulation capabilities.
Why Learn C++?
C++ remains one of the most important programming languages because:
1. Performance: Close to hardware with minimal abstraction
2. Control: Direct memory management and hardware access
3. Versatility: Supports multiple paradigms
4. Industry Standard: Used in operating systems, game engines, databases
5. Foundation: Understanding C++ makes learning other languages easier
The Anatomy of a C++ Program
Every C++ program follows a specific structure:
- Preprocessor Directives: Lines starting with
# - Namespace Declaration:
using namespace std; - Main Function:
int main() { ... return 0; } - Statements: Instructions ending with semicolons
- Comments:
//or/* */
The Compilation Process
C++ is a compiled language:
1. Preprocessing: Handles directives
2. Compilation: Translates to assembly
3. Assembly: Converts to machine code
4. Linking: Combines object files
Example: Hello World Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++ Programmer!";
cout << endl;
return 0;
}
Note: Every statement must end with a semicolon (;). The using namespace std; statement is convenient but in larger projects, it's better to use std:: explicitly.
02. 📦 Variables, Data Types & I/O
C++ is a statically typed language, meaning you must declare the data type of every variable before using it.
Fundamental Data Types
- Integer Types:
int,short,long,long long - Floating-Point:
float,double,long double - Character:
char - Boolean:
bool - Void:
void
Input/Output Streams
The <iostream> header provides stream-based I/O:
- cout: Standard output
- cin: Standard input
- cerr: Standard error
- clog: Standard logging
Example: Variable Declaration and I/O
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 25;
double salary = 45000.50;
char grade = 'A';
bool employed = true;
string name = "John Doe";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Salary: $" << salary << endl;
// Input example
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
cout << "Sum: " << (x + y) << endl;
return 0;
}
03. 🚦 Control Flow (If/Else/Switch)
Control flow statements allow your program to make decisions and execute different code paths based on conditions.
The if-else Statement Family
- Simple if: Executes if condition is true
- if-else: Alternative execution path
- if-else if-else: Multiple conditions
- Nested if: if statements inside other ifs
The switch Statement
Provides efficient way to select among multiple alternatives based on integer or character expression.
Example: Conditional Statements
#include <iostream>
using namespace std;
int main() {
int score = 85;
// if-else if ladder
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else if (score >= 60) {
cout << "Grade: D" << endl;
} else {
cout << "Grade: F" << endl;
}
// Switch statement
char grade = 'B';
switch(grade) {
case 'A': cout << "Excellent!"; break;
case 'B': cout << "Good!"; break;
case 'C': cout << "Fair"; break;
case 'D': cout << "Poor"; break;
case 'F': cout << "Fail"; break;
default: cout << "Invalid grade";
}
// Ternary operator
int a = 10, b = 20;
int max = (a > b) ? a : b;
cout << "Maximum: " << max << endl;
return 0;
}
04. 🔁 Iteration (For, While, Do-While)
Loops enable repetitive execution of code blocks. C++ provides three primary loop constructs.
Loop Types
- for loop: Count-controlled iteration
- while loop: Condition-controlled iteration
- do-while loop: Post-test iteration (executes at least once)
Loop Control Statements
break: Exits loop immediately
continue: Skips to next iteration
goto: Unconditional jump (avoid in most cases)
Example: Loop Structures
#include <iostream>
using namespace std;
int main() {
// For loop
cout << "Counting 1 to 5:" << endl;
for(int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl;
// While loop
int count = 1;
cout << "While loop counting:" << endl;
while(count <= 3) {
cout << "Count: " << count << endl;
count++;
}
// Do-while loop
int number;
do {
cout << "Enter positive number: ";
cin >> number;
} while(number <= 0);
// Nested loops
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
cout << "(" << i << "," << j << ") ";
}
cout << endl;
}
return 0;
}
05. ⚙️ Functions & Overloading
Functions are fundamental building blocks that encapsulate reusable code.
Function Components
1. Return Type: Data type of returned value
2. Function Name: Identifier
3. Parameters: Input values
4. Function Body: Executed code
5. Return Statement: Returns control and value
Function Overloading
C++ allows multiple functions with the same name but different parameters (different type, count, or order).
Example: Functions and Overloading
#include <iostream>
using namespace std;
// Function declaration
int add(int a, int b);
double add(double a, double b);
// Function with default argument
void display(string message = "Hello World!");
int main() {
cout << add(5, 3) << endl; // Calls int version
cout << add(2.5, 3.7) << endl; // Calls double version
display(); // Uses default argument
display("Custom message");
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
void display(string message) {
cout << message << endl;
}
06. 🗃️ Arrays & Strings
Arrays store fixed-size sequential collections of elements of the same type.
Array Characteristics
1. Contiguous Memory: Elements stored next to each other
2. Fixed Size: Size must be known at compile time
3. Zero-Based Indexing: First element at index 0
4. No Bounds Checking: Programmer's responsibility
C-Strings vs std::string
- C-Strings: Null-terminated character arrays
- std::string: C++ string class with dynamic resizing
Example: Arrays and Strings
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
// One-dimensional array
int numbers[5] = {1, 2, 3, 4, 5};
cout << "Array elements: ";
for(int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
// 2D array (matrix)
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
// C-string
char cstr[] = "Hello";
cout << "C-string: " << cstr << endl;
cout << "Length: " << strlen(cstr) << endl;
// C++ string
string cppstr = "World";
cppstr = "Hello " + cppstr;
cout << "C++ string: " << cppstr << endl;
cout << "Length: " << cppstr.length() << endl;
// Array of strings
string fruits[] = {"Apple", "Banana", "Cherry"};
for(int i = 0; i < 3; i++) {
cout << fruits[i] << endl;
}
return 0;
}
07. 🎯 Pointers & References (Memory)
Pointers provide direct access to memory addresses, enabling efficient data manipulation and dynamic memory allocation.
Pointer Operations
&: Address operator
*: Dereference operator
new: Dynamic memory allocation
delete: Memory deallocation
References vs Pointers
- References: Aliases for variables, must be initialized
- Pointers: Store memory addresses, can be null
Example: Pointers and References
#include <iostream>
using namespace std;
int main() {
int num = 42;
// Pointer
int* ptr = #
cout << "Value: " << num << endl;
cout << "Address: " << ptr << endl;
cout << "Value via pointer: " << *ptr << endl;
// Modify via pointer
*ptr = 100;
cout << "Modified value: " << num << endl;
// Reference
int& ref = num;
ref = 200;
cout << "Modified via reference: " << num << endl;
// Dynamic memory
int* dynArray = new int[5];
for(int i = 0; i < 5; i++) {
dynArray[i] = i * 10;
}
// Clean up
delete[] dynArray;
return 0;
}
08. 🏗️ Classes and Objects (OOP Fundamentals)
Object-Oriented Programming organizes code around "objects" rather than functions. C++ provides comprehensive OOP support.
Four Pillars of OOP
1. Encapsulation: Bundling data and methods
2. Abstraction: Hiding implementation details
3. Inheritance: Creating new from existing
4. Polymorphism: One interface, multiple forms
Classes vs Structures
- Class: Default access is
private - Struct: Default access is
public
Example: Class Implementation
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int rollNumber;
double marks;
public:
// Setter methods
void setName(string n) {
name = n;
}
void setRollNumber(int r) {
rollNumber = r;
}
void setMarks(double m) {
marks = m;
}
// Getter methods
string getName() {
return name;
}
int getRollNumber() {
return rollNumber;
}
double getMarks() {
return marks;
}
// Member function
void display() {
cout << "Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Marks: " << marks << endl;
}
};
int main() {
Student s1;
s1.setName("Alice");
s1.setRollNumber(101);
s1.setMarks(85.5);
s1.display();
// Direct access would cause error
// s1.name = "Bob"; // Error: private member
return 0;
}
09. 🔨 Constructors & Destructors
Constructors and destructors are special member functions that handle object initialization and cleanup.
Constructor Types
1. Default Constructor: No parameters
2. Parameterized Constructor: Takes parameters
3. Copy Constructor: Creates copy of object
4. Move Constructor: Transfers resources (C++11)
Destructor
Called when object is destroyed. Used for cleanup operations like releasing memory.
Example: Constructors and Destructors
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
double price;
public:
// Default constructor
Book() {
title = "Unknown";
author = "Unknown";
price = 0.0;
cout << "Default constructor called" << endl;
}
// Parameterized constructor
Book(string t, string a, double p) {
title = t;
author = a;
price = p;
cout << "Parameterized constructor called" << endl;
}
// Copy constructor
Book(const Book &b) {
title = b.title;
author = b.author;
price = b.price;
cout << "Copy constructor called" << endl;
}
// Destructor
~Book() {
cout << "Destructor called for: " << title << endl;
}
void display() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Price: $" << price << endl;
}
};
int main() {
// Using different constructors
Book b1; // Default constructor
Book b2("C++ Programming", "Bjarne Stroustrup", 49.99); // Parameterized
Book b3 = b2; // Copy constructor
b2.display();
b3.display();
// Objects will be destroyed when scope ends
return 0;
}
10. 🌳 Inheritance & Polymorphism
Inheritance allows creating new classes (derived) from existing classes (base). Polymorphism enables objects of different classes to be treated as objects of a common base class.
Inheritance Types
1. Single Inheritance: One base, one derived
2. Multiple Inheritance: Multiple bases, one derived
3. Multilevel Inheritance: Chain of inheritance
4. Hierarchical Inheritance: One base, multiple derived
5. Hybrid Inheritance: Combination of above
Polymorphism
- Compile-time: Function overloading, operator overloading
- Runtime: Virtual functions, function overriding
Example: Inheritance and Polymorphism
#include <iostream>
#include <string>
using namespace std;
// Base class
class Shape {
protected:
string color;
public:
Shape(string c) : color(c) {}
// Virtual function for polymorphism
virtual double area() {
return 0.0;
}
virtual void display() {
cout << "Shape Color: " << color << endl;
}
};
// Derived class 1
class Circle : public Shape {
private:
double radius;
public:
Circle(string c, double r) : Shape(c), radius(r) {}
double area() override {
return 3.14159 * radius * radius;
}
void display() override {
Shape::display();
cout << "Type: Circle" << endl;
cout << "Radius: " << radius << endl;
cout << "Area: " << area() << endl;
}
};
// Derived class 2
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(string c, double l, double w) : Shape(c), length(l), width(w) {}
double area() override {
return length * width;
}
void display() override {
Shape::display();
cout << "Type: Rectangle" << endl;
cout << "Length: " << length << endl;
cout << "Width: " << width << endl;
cout << "Area: " << area() << endl;
}
};
int main() {
// Using polymorphism
Shape* shapes[3];
shapes[0] = new Circle("Red", 5.0);
shapes[1] = new Rectangle("Blue", 4.0, 6.0);
shapes[2] = new Circle("Green", 3.0);
for(int i = 0; i < 3; i++) {
shapes[i]->display();
cout << endl;
}
// Clean up
for(int i = 0; i < 3; i++) {
delete shapes[i];
}
return 0;
}
Codcups
C++ Foundations Deep Dive