C++ Programming

This guide introduces the core concepts of C++ programming. It is structured to take you from the absolute basics to more advanced topics like object-oriented programming and memory management.


1. Introduction to C++

C++ is a general-purpose, compiled, statically-typed programming language developed by Bjarne Stroustrup in 1979 at Bell Labs. It was designed as an extension of the C language, adding object-oriented features while maintaining the efficiency and low-level control of C.

Key Features

  • Performance: Close-to-hardware execution speed makes it suitable for system software, game engines, and high-performance applications.
  • Control: Offers direct control over system resources and memory management.
  • Multi-paradigm: Supports procedural, functional, and object-oriented programming.

2. Setting Up the Environment

To write and run C++ programs, you need two main tools:
1. A Compiler: Translates your C++ code into machine code (e.g., GCC/G++ for Linux/MinGW for Windows, Clang, or MSVC for Windows).
2. An IDE or Text Editor: Software to write your code (e.g., Visual Studio, VS Code, CLion, or Code::Blocks).

Compiling via Command Line (GCC)

If you have GCC installed, you can compile a file named main.cpp using the terminal:

g++ -std=c++17 main.cpp -o my_program
./my_program

3. Basic Syntax and "Hello World"

Let us examine a standard C++ program.

#include <iostream> // Header file library for input and output

int main() {
    // std::cout is used to print text to the console
    std::cout << "Hello, World!" << std::endl; 
    
    return 0; // Indicates that the program ended successfully
}

Key Components:

  • #include <iostream>: This line tells the preprocessor to include the Standard Input/Output Stream library, which allows us to use std::cout.
  • int main(): The entry point of every C++ program. Execution begins here.
  • std::cout: The character output stream. The << operator sends the string to the console.
  • std::endl: Inserts a newline character and flushes the output buffer. Alternatively, \n can be used.
  • return 0: Returns an exit status to the operating system.

4. Variables, Data Types, and Operators

C++ is statically typed, meaning you must declare the type of a variable before using it.

Common Data Types

TypeDescriptionSize (Typical)Example
intInteger (whole numbers)4 bytesint age = 25;
doubleFloating-point (decimal)8 bytesdouble price = 19.99;
charSingle character1 bytechar grade = 'A';
boolBoolean (true/false)1 bytebool isCoding = true;
std::stringSequence of charactersVariablestd::string name = "Alice";

Input and Output Example

To read input from the user, use std::cin.

#include <iostream>
#include <string>

int main() {
    std::string name;
    int age;

    std::cout << "Enter your name: ";
    std::cin >> name; // Reads a single word

    std::cout << "Enter your age: ";
    std::cin >> age;

    std::cout << "Hello " << name << ", you are " << age << " years old." << std::endl;

    return 0;
}

5. Control Flow

Control structures decide the execution path of the code based on conditions.

Conditional Statements (if, else if, else)

int score = 85;

if (score >= 90) {
    std::cout << "Grade: A" << std::endl;
} else if (score >= 80) {
    std::cout << "Grade: B" << std::endl;
} else {
    std::cout << "Grade: C or lower" << std::endl;
}

Loops

1. for Loop (Used when the number of iterations is known)

for (int i = 0; i < 5; ++i) {
    std::cout << "Iteration: " << i << std::endl;
}

2. while Loop (Used when looping depends on a condition)

int count = 0;
while (count < 3) {
    std::cout << "Count: " << count << std::endl;
    count++;
}

6. Functions

Functions allow you to group code into reusable blocks.

#include <iostream>

// Declaration (Prototype)
int addNumbers(int a, int b);

int main() {
    int result = addNumbers(5, 7);
    std::cout << "Sum: " << result << std::endl;
    return 0;
}

// Definition
int addNumbers(int a, int b) {
    return a + b;
}

Pass by Value vs. Pass by Reference

  • Pass by Value: A copy of the argument is passed. Changes inside the function do not affect the original variable.
  • Pass by Reference: A reference to the actual variable is passed using the & operator. Changes inside the function affect the original variable.
void updateValue(int &num) {
    num = 100; // This modifies the original variable passed to it
}

7. Pointers and References

Pointers are one of C++'s most powerful, yet challenging, features.

Pointers

A pointer is a variable that stores the memory address of another variable.

  • & (Address-of operator): Gets the address of a variable.
  • * (Dereference operator): Accesses the value stored at the address.
int var = 42;
int* ptr = &var; // ptr stores the address of var

std::cout << "Address of var: " << ptr << std::endl;
std::cout << "Value of var: " << *ptr << std::endl; // Output: 42

References

A reference is an alias (another name) for an existing variable. It must be initialized when declared and cannot be changed to refer to another variable.

int original = 10;
int &ref = original; // ref is an alias for original

ref = 20; // Now original is also 20

8. Object-Oriented Programming (OOP)

C++ supports Object-Oriented Programming, which organizes software design around data, or objects, rather than functions and logic.

Classes and Objects

A class is a blueprint, and an object is an instance of that blueprint.

#include <iostream>
#include <string>

class Book {
private:
    std::string title; // Private member variable
    std::string author;

public:
    // Constructor
    Book(std::string t, std::string a) {
        title = t;
        author = a;
    }

    // Method to display information
    void displayInfo() {
        std::cout << "Title: " << title << ", Author: " << author << std::endl;
    }
};

int main() {
    // Creating an object of Book
    Book book1("1984", "George Orwell");
    book1.displayInfo();

    return 0;
}

Key OOP Pillars

1. Encapsulation: Keeping data (variables) and behavior (functions) grouped together inside a class, restricting direct access using private or protected specifiers.
2. Inheritance: Creating new classes based on existing classes to reuse code.
3. Polymorphism: Allowing different classes to respond to the same function call in their own way (typically achieved using virtual functions).


9. Dynamic Memory Management

In C++, you can allocate memory manually on the heap during runtime using new and free it using delete. This is useful when the size of data is not known at compile-time.

int* ptr = new int; // Dynamically allocate an integer
*ptr = 25;

std::cout << "Value: " << *ptr << std::endl;

delete ptr; // Deallocate memory to avoid memory leaks
ptr = nullptr; // Reset the pointer

Note: For modern C++, it is generally recommended to use smart pointers (std::uniqueptr, std::sharedptr) from the <memory> header to manage dynamic memory automatically and reduce memory leaks.


10. Introduction to the Standard Template Library (STL)

The STL is a collection of template classes and functions that provide common data structures and algorithms.

Vectors (Dynamic Arrays)

Unlike standard arrays, vectors can change size dynamically.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3};

    numbers.push_back(4); // Add 4 to the end
    numbers.push_back(5); // Add 5 to the end

    for (int num : numbers) {
        std::cout << num << " "; // Output: 1 2 3 4 5
    }
    std::cout << std::endl;

    return 0;
}

The guide was created in June 2026.