Beginner to Advanced45 min read

C++ Programming — The Ultimate Guide

C++ combines the raw power of C with modern abstractions like classes, templates, and the Standard Template Library. It is the language behind game engines, browsers, databases, and high-performance systems. This guide takes you from zero to confident C++ programmer with working code examples.

What Is C++?

C++ is a general-purpose programming language created by Bjarne Stroustrup in 1979 as an extension of C. Originally called "C with Classes," it adds object-oriented programming, generic programming via templates, and the Standard Template Library (STL) to the C foundation.

C++ is one of the most widely used languages in the world. It powers game engines, web browsers, operating systems, databases, embedded systems, and financial trading platforms. The latest standard, C++23, continues to modernize the language with features like concepts, ranges, and coroutines.

Why Learn C++?

  • Performance — C++ compiles to native machine code with zero-cost abstractions. It is as fast as C but with better tooling.
  • Game development — Unreal Engine, the most popular game engine, is written entirely in C++.
  • Systems programming — Operating systems, browsers, and databases use C++ for performance-critical code.
  • Competitive programming — C++ is the dominant language in competitive programming due to its speed and the STL.
  • Interview preparation — Top tech companies test C++ concepts extensively in coding interviews.
  • Career opportunities — C++ developers are among the highest-paid programmers in the industry.

Your First C++ Program

#include <iostream>
#include <string>

int main() {
    std::string name = "CodePractise";
    std::cout << "Hello, " << name << "!" << std::endl;

    // Using namespace std (common in tutorials)
    using namespace std;
    cout << "Welcome to C++ programming!" << endl;

    return 0;
}

Key differences from C: C++ uses #include <iostream> instead of stdio.h, and uses std::cout instead of printf().

Variables and Data Types

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Fundamental types
    int age = 25;
    double pi = 3.14159265358979;
    float small_pi = 3.14f;
    char letter = 'A';
    bool is_active = true;
    string name = "CodePractise";

    // auto keyword (C++11) — type inference
    auto score = 95;          // int
    auto price = 19.99;       // double
    auto greeting = "Hello";  // const char*

    // Constant
    const int MAX_SIZE = 100;

    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Pi: " << pi << endl;
    cout << "Active: " << is_active << endl;
    cout << "Size of int: " << sizeof(int) << " bytes" << endl;

    return 0;
}

Control Flow

#include <iostream>
using namespace std;

int main() {
    // If-else
    int score = 85;
    if (score >= 90) cout << "Grade: A" << endl;
    else if (score >= 80) cout << "Grade: B" << endl;
    else cout << "Grade: C" << endl;

    // Switch
    int day = 3;
    switch (day) {
        case 1: cout << "Monday" << endl; break;
        case 2: cout << "Tuesday" << endl; break;
        case 3: cout << "Wednesday" << endl; break;
        default: cout << "Other day" << endl; break;
    }

    // Range-based for loop (C++11)
    int nums[] = {10, 20, 30, 40, 50};
    for (int n : nums) {
        cout << n << " ";
    }
    cout << endl;

    return 0;
}

Functions

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

// Function with default parameters
int power(int base, int exp = 2) {
    int result = 1;
    for (int i = 0; i < exp; i++) result *= base;
    return result;
}

// Overloaded function
double power(double base, int exp) {
    double result = 1.0;
    for (int i = 0; i < exp; i++) result *= base;
    return result;
}

// Lambda function (C++11)
auto multiply = [](int a, int b) { return a * b; };

int main() {
    cout << "2^3 = " << power(2, 3) << endl;
    cout << "5^2 = " << power(5) << endl;    // uses default exp=2
    cout << "2.5^3 = " << power(2.5, 3) << endl;
    cout << "4 * 7 = " << multiply(4, 7) << endl;

    return 0;
}

Classes and Objects (OOP)

C++ is fundamentally an object-oriented language. Classes encapsulate data and behavior into reusable blueprints:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class BankAccount {
private:
    string owner;
    double balance;

public:
    // Constructor
    BankAccount(string name, double initial_balance)
        : owner(name), balance(initial_balance) {}

    // Methods
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "Deposited $" << amount << ". Balance: $" << balance << endl;
        }
    }

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            cout << "Withdrew $" << amount << ". Balance: $" << balance << endl;
        } else {
            cout << "Insufficient funds!" << endl;
        }
    }

    void display() const {
        cout << owner << ": $" << balance << endl;
    }

    // Getter
    double getBalance() const { return balance; }
};

int main() {
    BankAccount acc("Alice", 1000.0);
    acc.display();
    acc.deposit(500);
    acc.withdraw(200);
    acc.display();

    return 0;
}

Inheritance and Polymorphism

#include <iostream>
#include <string>
using namespace std;

class Animal {
public:
    virtual void speak() {
        cout << "..." << endl;
    }
    virtual ~Animal() {}
};

class Dog : public Animal {
public:
    void speak() override {
        cout << "Woof!" << endl;
    }
};

class Cat : public Animal {
public:
    void speak() override {
        cout << "Meow!" << endl;
    }
};

int main() {
    Animal* animals[] = { new Dog(), new Cat(), new Animal() };

    for (Animal* a : animals) {
        a->speak();  // Polymorphic call
    }

    for (Animal* a : animals) delete a;
    return 0;
}

The Standard Template Library (STL)

The STL is C++ superpower. It provides ready-to-use containers, algorithms, and iterators that save you from implementing everything from scratch:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;

int main() {
    // Vector — dynamic array
    vector<int> nums = {5, 2, 8, 1, 9, 3};
    sort(nums.begin(), nums.end());

    cout << "Sorted: ";
    for (int n : nums) cout << n << " ";
    cout << endl;

    // Map — key-value pairs
    map<string, int> ages;
    ages["Alice"] = 25;
    ages["Bob"] = 30;
    ages["Charlie"] = 22;

    for (auto& [name, age] : ages) {
        cout << name << ": " << age << endl;
    }

    // Set — unique sorted elements
    set<int> unique_nums = {5, 2, 8, 2, 5, 1};
    cout << "Unique: ";
    for (int n : unique_nums) cout << n << " ";
    cout << endl;

    // Stack
    stack<string> history;
    history.push("google.com");
    history.push("github.com");
    history.push("codepractise.online");
    cout << "Current: " << history.top() << endl;

    // Queue
    queue<string> tasks;
    tasks.push("Write code");
    tasks.push("Run tests");
    tasks.push("Deploy");
    cout << "Next: " << tasks.front() << endl;

    return 0;
}

Pointers and References

#include <iostream>
using namespace std;

void increment(int& val) {  // pass by reference
    val++;
}

void swap_values(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 10;
    int* ptr = &x;   // pointer to x
    int& ref = x;    // reference to x

    cout << "x = " << x << endl;
    cout << "*ptr = " << *ptr << endl;
    cout << "ref = " << ref << endl;

    *ptr = 20;
    cout << "After *ptr = 20: x = " << x << endl;

    increment(x);
    cout << "After increment: x = " << x << endl;

    int a = 5, b = 10;
    swap_values(a, b);
    cout << "After swap: a = " << a << ", b = " << b << endl;

    return 0;
}

Templates

Templates let you write generic code that works with any data type:

#include <iostream>
#include <string>
using namespace std;

// Function template
template <typename T>
T find_max(T a, T b) {
    return (a > b) ? a : b;
}

// Class template
template <typename T>
class Stack {
    T items[100];
    int top = -1;
public:
    void push(T item) { items[++top] = item; }
    T pop() { return items[top--]; }
    bool empty() { return top == -1; }
    T peek() { return items[top]; }
};

int main() {
    cout << "Max of 3, 7: " << find_max(3, 7) << endl;
    cout << "Max of 3.14, 2.71: " << find_max(3.14, 2.71) << endl;
    cout << "Max of 'a', 'z': " << find_max('a', 'z') << endl;

    Stack<int> s;
    s.push(10);
    s.push(20);
    s.push(30);
    cout << "Top: " << s.peek() << endl;

    return 0;
}

File I/O

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    // Write to file
    ofstream outfile("data.txt");
    outfile << "Language: C++" << endl;
    outfile << "Version: C++23" << endl;
    outfile << "Rating: 5/5" << endl;
    outfile.close();

    // Read from file
    ifstream infile("data.txt");
    string line;
    while (getline(infile, line)) {
        cout << line << endl;
    }
    infile.close();

    return 0;
}

Modern C++ Features

C++11 and later introduced features that make the language safer and more expressive:

#include <iostream>
#include <vector>
#include <memory>
#include <optional>
using namespace std;

int main() {
    // Smart pointers — automatic memory management
    auto ptr = make_unique<string>("Hello, C++!");
    cout << *ptr << endl;

    // Structured bindings (C++17)
    pair<string, int> person = {"Alice", 25};
    auto [name, age] = person;
    cout << name << " is " << age << endl;

    // Optional (C++17)
    optional<int> find_value(bool found) {
        if (found) return 42;
        return nullopt;
    }

    auto result = find_value(true);
    if (result.has_value()) {
        cout << "Found: " << *result << endl;
    }

    // Range-based for with initializer (C++20)
    for (auto& [key, value] : map<string, int>{{"a", 1}, {"b", 2}}) {
        cout << key << ": " << value << endl;
    }

    return 0;
}

C++ vs Other Languages

FeatureC++CPythonJava
ParadigmOOP + GenericProceduralMulti-paradigmOOP
MemoryManual + RAIIManualGarbage CollectedGarbage Collected
SpeedVery FastVery FastSlowFast
STL / LibrariesBuilt-in STLMinimalExtensiveExtensive
CompilationCompiledCompiledInterpretedCompiled to bytecode
Use CaseGames, SystemsSystemsGeneralEnterprise

C++ Interview Questions

  1. What is the difference between map and unordered_map?map is ordered (red-black tree, O(log n)); unordered_map is a hash table (average O(1)).
  2. What is RAII? — Resource Acquisition Is Initialization. Tie resource lifetime to object scope so cleanup happens automatically.
  3. What are smart pointers?unique_ptr, shared_ptr, and weak_ptr automate memory management and prevent leaks.
  4. What is the difference between struct and class? — In C++, the only difference is default access: struct members are public by default; class members are private.
  5. What is a virtual function? — A function declared with virtual that enables runtime polymorphism. The correct derived-class version is called via a base-class pointer.

Cheat Sheet

ConceptSyntax
Include#include <iostream>
Namespaceusing namespace std;
Outputcout << "text" << endl;
Variableauto x = 10;
Classclass Foo { public: int x; };
Vectorvector<int> v = {1, 2, 3};
Mapmap<string, int> m;
For loopfor (auto& x : vec) { ... }
Lambdaauto f = [](int x) { return x * 2; };
Smart Pointerauto p = make_unique<T>(args);
Templatetemplate <typename T> T func(T a);

Practice Problems

  1. Two Sum — Find two numbers in an array that add up to a target.
  2. Reverse String — Reverse a string in place using two pointers.
  3. Linked List — Implement a singly linked list with insert, delete, and search.
  4. BST Operations — Implement insert, search, and in-order traversal.
  5. Graph BFS — Implement breadth-first search on an adjacency list.
  6. LRU Cache — Design an LRU cache using a hash map and doubly linked list.

Related Tutorials

Want to Run Code?

Practice C++ concepts with our Python compiler. Write, run, and experiment with code instantly — no sign-up required.

Try Our Online Compiler →

FAQ

What is C++ used for?

C++ is used for game engines (Unreal Engine, Unity), browsers (Chrome, Firefox), operating systems, databases (MongoDB, MySQL), embedded systems, high-frequency trading, graphics applications (Adobe, Photoshop), and performance-critical software where both speed and abstraction are needed.

How to run C++ code online?

You can run C++ code online using platforms like CodePractise, Compiler Explorer (godbolt.org), or OnlineGDB. Write your C++ code in the editor, compile, and see the output. Our Python compiler also lets you practice algorithmic problems while learning C++ concepts.

Is C++ harder than Python?

Yes, C++ has a steeper learning curve than Python due to manual memory management, pointers, templates, and complex syntax. However, C++ teaches you deeper computer science concepts that make you a stronger programmer overall.

What is the STL in C++?

The Standard Template Library (STL) provides ready-to-use data structures (vector, map, set, stack, queue) and algorithms (sort, search, transform). It saves you from implementing common data structures from scratch and is one of C++ biggest strengths.

What companies use C++?

Major companies using C++ include Google (Chrome, Android), Microsoft (Windows, Office), Epic Games (Unreal Engine), Adobe (Photoshop, Illustrator), Facebook (HHVM), Bloomberg, Goldman Sachs, Amazon, and Netflix for performance-critical backend systems.