C++ Programming Documentation
Comprehensive guide to C++ programming language
Basic C++ Concepts
This module covers the fundamental building blocks of C++ programming including variables, data types, operators, control structures, and functions.
Basic Data Types
| Type | Description | Size | Example |
|---|---|---|---|
int |
Integer | 4 bytes | int age = 25; |
float |
Single precision floating point | 4 bytes | float price = 19.99f; |
double |
Double precision floating point | 8 bytes | double pi = 3.14159; |
char |
Single character | 1 byte | char grade = 'A'; |
bool |
Boolean (true/false) | 1 byte | bool isReady = true; |
string |
Text string | Variable | string name = "John"; |
Variable Declaration and Initialization
#include <iostream>
#include <string>
int main() {
// Declaration and initialization
int age = 25;
double salary = 50000.50;
char grade = 'A';
bool isEmployed = true;
std::string name = "John Doe";
// Output variables
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Salary: $" << salary << std::endl;
std::cout << "Grade: " << grade << std::endl;
std::cout << "Employed: " << std::boolalpha << isEmployed << std::endl;
// Constants
const double PI = 3.14159;
const int MAX_STUDENTS = 100;
std::cout << "PI: " << PI << std::endl;
std::cout << "Max students: " << MAX_STUDENTS << std::endl;
return 0;
}
Arithmetic Operators
#include <iostream>
int main() {
int a = 10, b = 3;
// Arithmetic operations
std::cout << "Addition: " << (a + b) << std::endl; // 13
std::cout << "Subtraction: " << (a - b) << std::endl; // 7
std::cout << "Multiplication: " << (a * b) << std::endl; // 30
std::cout << "Division: " << (a / b) << std::endl; // 3 (integer division)
std::cout << "Modulus: " << (a % b) << std::endl; // 1 (remainder)
// Floating point division
double c = 10.0, d = 3.0;
std::cout << "Float division: " << (c / d) << std::endl; // 3.33333
return 0;
}
Comparison Operators
#include <iostream>
int main() {
int x = 5, y = 10;
std::cout << "Equal: " << (x == y) << std::endl; // false (0)
std::cout << "Not equal: " << (x != y) << std::endl; // true (1)
std::cout << "Greater than: " << (x > y) << std::endl; // false (0)
std::cout << "Less than: " << (x < y) << std::endl; // true (1)
std::cout << "Greater or equal: " << (x >= y) << std::endl; // false (0)
std::cout << "Less or equal: " << (x <= y) << std::endl; // true (1)
return 0;
}
Logical Operators
#include <iostream>
int main() {
bool a = true, b = false;
std::cout << "AND: " << (a && b) << std::endl; // false (0)
std::cout << "OR: " << (a || b) << std::endl; // true (1)
std::cout << "NOT a: " << (!a) << std::endl; // false (0)
std::cout << "NOT b: " << (!b) << std::endl; // true (1)
return 0;
}
Assignment Operators
#include <iostream>
int main() {
int x = 10;
// Assignment operators
x += 5; // x = x + 5; (x = 15)
std::cout << "After += 5: " << x << std::endl;
x -= 3; // x = x - 3; (x = 12)
std::cout << "After -= 3: " << x << std::endl;
x *= 2; // x = x * 2; (x = 24)
std::cout << "After *= 2: " << x << std::endl;
x /= 4; // x = x / 4; (x = 6)
std::cout << "After /= 4: " << x << std::endl;
x %= 4; // x = x % 4; (x = 2)
std::cout << "After %= 4: " << x << std::endl;
return 0;
}
if Statement
#include <iostream>
int main() {
int age = 18;
if (age >= 18) {
std::cout << "You are eligible to vote!" << std::endl;
} else {
std::cout << "You are not eligible to vote yet." << std::endl;
}
return 0;
}
if-else if-else Statement
#include <iostream>
int main() {
int score = 85;
if (score >= 90) {
std::cout << "Grade: A" << std::endl;
} else if (score >= 80) {
std::cout << "Grade: B" << std::endl;
} else if (score >= 70) {
std::cout << "Grade: C" << std::endl;
} else if (score >= 60) {
std::cout << "Grade: D" << std::endl;
} else {
std::cout << "Grade: F" << std::endl;
}
return 0;
}
switch Statement
#include <iostream>
int main() {
char grade = 'B';
switch (grade) {
case 'A':
std::cout << "Excellent!" << std::endl;
break;
case 'B':
std::cout << "Good!" << std::endl;
break;
case 'C':
std::cout << "Average!" << std::endl;
break;
case 'D':
std::cout << "Below Average!" << std::endl;
break;
case 'F':
std::cout << "Fail!" << std::endl;
break;
default:
std::cout << "Invalid grade!" << std::endl;
}
return 0;
}
Ternary Operator
#include <iostream>
int main() {
int age = 20;
std::string message = (age >= 18) ? "Adult" : "Minor";
std::cout << "Status: " << message << std::endl;
return 0;
}
for Loop
#include <iostream>
int main() {
// Basic for loop
for (int i = 1; i <= 5; i++) {
std::cout << "Count: " << i << std::endl;
}
// Nested for loop
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
std::cout << i << " * " << j << " = " << (i * j) << std::endl;
}
std::cout << "---" << std::endl;
}
return 0;
}
while Loop
#include <iostream>
int main() {
int count = 1;
// while loop
while (count <= 5) {
std::cout << "Count: " << count << std::endl;
count++;
}
// Input validation with while loop
int number;
std::cout << "Enter a positive number: ";
std::cin >> number;
while (number <= 0) {
std::cout << "Invalid! Please enter a positive number: ";
std::cin >> number;
}
std::cout << "You entered: " << number << std::endl;
return 0;
}
do-while Loop
#include <iostream>
int main() {
int choice;
do {
std::cout << "\nMenu:" << std::endl;
std::cout << "1. Option 1" << std::endl;
std::cout << "2. Option 2" << std::endl;
std::cout << "3. Exit" << std::endl;
std::cout << "Enter your choice: ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "You selected Option 1" << std::endl;
break;
case 2:
std::cout << "You selected Option 2" << std::endl;
break;
case 3:
std::cout << "Exiting..." << std::endl;
break;
default:
std::cout << "Invalid choice!" << std::endl;
}
} while (choice != 3);
return 0;
}
Loop Control Statements
#include <iostream>
int main() {
// break statement
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit the loop when i equals 6
}
std::cout << i << " ";
}
std::cout << "\n";
// continue statement
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
std::cout << i << " ";
}
std::cout << "\n";
return 0;
}
One-Dimensional Arrays
#include <iostream>
int main() {
// Declaration and initialization
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing array elements
std::cout << "First element: " << numbers[0] << std::endl;
std::cout << "Third element: " << numbers[2] << std::endl;
// Modifying array elements
numbers[1] = 25;
std::cout << "Modified second element: " << numbers[1] << std::endl;
// Iterating through an array
std::cout << "All elements: ";
for (int i = 0; i < 5; i++) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
// Range-based for loop (C++11 and later)
std::cout << "Using range-based for loop: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Multi-Dimensional Arrays
#include <iostream>
int main() {
// 2D array
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing 2D array elements
std::cout << "Element at [1][2]: " << matrix[1][2] << std::endl;
// Iterating through a 2D array
std::cout << "Matrix:" << std::endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
Array Operations
#include <iostream>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int size = 5;
// Find sum
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
std::cout << "Sum: " << sum << std::endl;
// Find maximum
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
std::cout << "Maximum: " << max << std::endl;
// Find minimum
int min = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
std::cout << "Minimum: " << min << std::endl;
return 0;
}
Function Declaration and Definition
#include <iostream>
// Function declaration (prototype)
int add(int a, int b);
double multiply(double x, double y);
void greet(std::string name);
int main() {
// Calling functions
int result1 = add(5, 3);
std::cout << "5 + 3 = " << result1 << std::endl;
double result2 = multiply(2.5, 4.0);
std::cout << "2.5 * 4.0 = " << result2 << std::endl;
greet("Alice");
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
double multiply(double x, double y) {
return x * y;
}
void greet(std::string name) {
std::cout << "Hello, " << name << "!" << std::endl;
}
Function with Default Parameters
#include <iostream>
// Function with default parameters
void printMessage(std::string message, int times = 1) {
for (int i = 0; i < times; i++) {
std::cout << message << std::endl;
}
}
int main() {
printMessage("Hello!"); // Uses default times = 1
printMessage("Hi!", 3); // Uses provided times = 3
return 0;
}
Function Overloading
#include <iostream>
// Function overloading
int calculate(int a, int b) {
return a + b;
}
double calculate(double a, double b) {
return a * b;
}
int calculate(int a, int b, int c) {
return a + b + c;
}
int main() {
std::cout << "calculate(5, 3): " << calculate(5, 3) << std::endl;
std::cout << "calculate(2.5, 4.0): " << calculate(2.5, 4.0) << std::endl;
std::cout << "calculate(1, 2, 3): " << calculate(1, 2, 3) << std::endl;
return 0;
}
Pass by Value vs Pass by Reference
#include <iostream>
// Pass by value
void incrementByValue(int x) {
x++;
std::cout << "Inside function (by value): " << x << std::endl;
}
// Pass by reference
void incrementByReference(int &x) {
x++;
std::cout << "Inside function (by reference): " << x << std::endl;
}
int main() {
int num1 = 10;
int num2 = 10;
std::cout << "Before call (by value): " << num1 << std::endl;
incrementByValue(num1);
std::cout << "After call (by value): " << num1 << std::endl;
std::cout << "\nBefore call (by reference): " << num2 << std::endl;
incrementByReference(num2);
std::cout << "After call (by reference): " << num2 << std::endl;
return 0;
}
Basic Input/Output
#include <iostream>
#include <string>
int main() {
// Output
std::cout << "Hello, World!" << std::endl;
std::cout << "This is a C++ program." << std::endl;
// Input
std::string name;
int age;
std::cout << "Enter your name: ";
std::getline(std::cin, name); // Read entire line including spaces
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl;
return 0;
}
Formatted Output
#include <iostream>
#include <iomanip> // For formatting
int main() {
double pi = 3.14159265359;
// Set precision
std::cout << std::fixed << std::setprecision(2);
std::cout << "Pi to 2 decimal places: " << pi << std::endl;
// Set width and alignment
std::cout << std::setw(10) << std::left << "Name:"
<< std::setw(10) << std::right << "Age:" << std::endl;
std::cout << std::setw(10) << std::left << "John:"
<< std::setw(10) << std::right << "25:" << std::endl;
return 0;
}
Input Validation
#include <iostream>
#include <limits> // For numeric_limits
int main() {
int number;
std::cout << "Enter an integer: ";
// Input validation loop
while (!(std::cin >> number)) {
std::cout << "Invalid input! Please enter an integer: ";
std::cin.clear(); // Clear error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Discard bad input
}
std::cout << "You entered: " << number << std::endl;
return 0;
}
What is C++?
C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language. It was first released in 1985 as "C with Classes" and has since evolved into a powerful, multi-paradigm language supporting procedural, object-oriented, generic, and functional programming.
History of C++
- 1979: Bjarne Stroustrup begins work on "C with Classes"
- 1985: First commercial release of C++
- 1998: C++ standardization by ISO/IEC
- 2011: C++11 standard with new features
- 2014: C++14 standard with improvements
- 2017: C++17 standard with more features
- 2020: C++20 standard with major additions
Features of C++
- Object-Oriented Programming: Encapsulation, inheritance, polymorphism
- Generic Programming: Templates for type-independent code
- High Performance: Low-level memory manipulation
- Type Safety: Strong typing and compile-time checks
- Standard Library: Rich set of containers and algorithms
- Compatibility: Largely compatible with C code
Your First C++ Program
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
# Compile the program
g++ hello.cpp -o hello
# Run the program
./hello
Classes and Objects in C++
Classes are blueprints for creating objects. An object is an instance of a class. Classes encapsulate data (attributes) and functions (methods) that operate on that data.
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
public:
// Constructor
Student(std::string n, int a) {
name = n;
age = a;
}
// Method
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
// Getter methods
std::string getName() {
return name;
}
int getAge() {
return age;
}
// Setter methods
void setName(std::string n) {
name = n;
}
void setAge(int a) {
age = a;
}
};
int main() {
// Create an object
Student student1("John", 20);
// Call method
student1.displayInfo();
// Use getter methods
std::cout << "Name: " << student1.getName() << std::endl;
std::cout << "Age: " << student1.getAge() << std::endl;
// Use setter methods
student1.setName("Jane");
student1.setAge(22);
student1.displayInfo();
return 0;
}
#include <iostream>
#include <string>
class Rectangle {
private:
double length;
double width;
public:
// Default constructor
Rectangle() : length(0.0), width(0.0) {
std::cout << "Default constructor called" << std::endl;
}
// Parameterized constructor
Rectangle(double l, double w) : length(l), width(w) {
std::cout << "Parameterized constructor called" << std::endl;
}
// Copy constructor
Rectangle(const Rectangle& other) : length(other.length), width(other.width) {
std::cout << "Copy constructor called" << std::endl;
}
// Destructor
~Rectangle() {
std::cout << "Destructor called" << std::endl;
}
double getArea() {
return length * width;
}
};
int main() {
// Create objects using different constructors
Rectangle rect1; // Default constructor
Rectangle rect2(5.0, 3.0); // Parameterized constructor
Rectangle rect3 = rect2; // Copy constructor
std::cout << "Area of rect1: " << rect1.getArea() << std::endl;
std::cout << "Area of rect2: " << rect2.getArea() << std::endl;
std::cout << "Area of rect3: " << rect3.getArea() << std::endl;
return 0;
}
Inheritance and Polymorphism in C++
Inheritance allows a class to inherit properties and methods from another class. Polymorphism allows objects of different classes to be treated as objects of a common base class.
#include <iostream>
#include <string>
// Base class
class Animal {
protected:
std::string name;
public:
Animal(std::string n) : name(n) {
std::cout << "Animal constructor called" << std::endl;
}
virtual void makeSound() {
std::cout << "Some generic animal sound" << std::endl;
}
std::string getName() {
return name;
}
};
// Derived class
class Dog : public Animal {
public:
Dog(std::string n) : Animal(n) {
std::cout << "Dog constructor called" << std::endl;
}
void makeSound() override {
std::cout << "Woof! Woof!" << std::endl;
}
};
int main() {
Animal* animalPtr;
// Create objects
Dog dog("Buddy");
// Use base class pointer to derived class objects
animalPtr = &dog;
animalPtr->makeSound(); // Calls Dog's makeSound method
return 0;
}
Templates in C++
Templates allow you to write generic functions and classes that can work with different data types. Templates are a powerful feature of C++ that enables generic programming.
#include <iostream>
// Function template
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
// Use function template with integers
int sum = add(5, 3);
std::cout << "Sum of 5 and 3: " << sum << std::endl;
return 0;
}
Exception Handling in C++
C++ provides a robust exception handling mechanism to handle runtime errors gracefully without crashing the program.
#include <iostream>
#include <stdexcept>
int main() {
try {
// Code that might throw an exception
int denominator = 0;
if (denominator == 0) {
throw std::runtime_error("Division by zero");
}
int result = 10 / denominator;
std::cout << "Result: " << result << std::endl;
}
catch (const std::runtime_error& e) {
std::cerr << "Runtime error: " << e.what() << std::endl;
}
return 0;
}
Standard Template Library (STL)
The Standard Template Library (STL) is a collection of template classes that provide common data structures and algorithms. It is part of the C++ standard library.
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
int main() {
// Vector
std::vector<int> vec = {1, 2, 3, 4, 5};
std::cout << "Vector elements: ";
for (const auto& item : vec) {
std::cout << item << " ";
}
std::cout << std::endl;
// List
std::list<std::string> list = {"apple", "banana", "cherry"};
std::cout << "List elements: ";
for (const auto& item : list) {
std::cout << item << " ";
}
std::cout << std::endl;
return 0;
}
File I/O in C++
C++ provides robust file I/O capabilities through the fstream library for text files and binary files.
#include <iostream>
#include <fstream>
#include <string>
int main() {
// Writing to a text file
std::ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, World!" << std::endl;
outFile.close();
}
// Reading from a text file
std::ifstream inFile("example.txt");
if (inFile.is_open()) {
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
}
return 0;
}
Memory Management in C++
C++ provides both manual memory management through pointers and automatic memory management through smart pointers and RAII (Resource Acquisition Is Initialization).
#include <iostream>
int main() {
// Allocate memory
int* ptr = new int(10);
// Use the memory
*ptr = 20;
std::cout << "Value: " << *ptr << std::endl;
// Free the memory
delete ptr;
ptr = nullptr; // Set pointer to null after deletion
return 0;
}
Advanced C++ Topics
This module covers advanced C++ concepts that enhance your programming capabilities.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Simple lambda expression
auto add = [](int a, int b) { return a + b; };
std::cout << "5 + 3 = " << add(5, 3) << std::endl;
return 0;
}
Real-world C++ Applications
C++ is widely used in various domains due to its performance, control, and versatility. Here are some real-world applications of C++:
C++ is the language of choice for game development due to its performance and control over hardware. Many popular game engines are built with C++:
- Unreal Engine
- Unity (core components)
- CryEngine
- Godot (core components)
#include <iostream>
class GameObject {
protected:
std::string name;
float x, y;
public:
GameObject(std::string n, float xPos, float yPos)
: name(n), x(xPos), y(yPos) {}
virtual void update() {
std::cout << "Updating " << name << " at position ("
<< x << ", " << y << ")" << std::endl;
}
};
class Player : public GameObject {
private:
int health;
public:
Player(std::string n, float xPos, float yPos, int h)
: GameObject(n, xPos, yPos), health(h) {}
void update() override {
// Update player position
x += 0.1f;
y += 0.05f;
std::cout << "Player " << name << " moved to ("
<< x << ", " << y << ") with health "
<< health << std::endl;
}
};
int main() {
Player player("Hero", 0.0f, 0.0f, 100);
// Game loop simulation
for (int i = 0; i < 5; i++) {
player.update();
}
return 0;
}