C++ Language Reference

Introduction to C++

C++ is a powerful, general-purpose programming language created by Bjarne Stroustrup. It is an extension of the C language, providing object-oriented features, generic programming capabilities, and low-level memory manipulation. C++ is widely used for systems programming, game development, embedded systems, high-performance computing, and application development.

This documentation provides a comprehensive guide to the C++ language, its features, standard library, and best practices.

Core Concepts

  • Object-Oriented Programming (OOP): Encapsulation, Inheritance, Polymorphism.
  • Generic Programming: Using templates to write code that works with different types.
  • Memory Management: Pointers, references, dynamic memory allocation (new, delete), smart pointers.
  • Type System: Strong typing, data types, type conversions.
  • Standard Template Library (STL): Containers, algorithms, iterators.

Language Features

Data Types

C++ offers a rich set of built-in data types, including integral types (int, char, bool), floating-point types (float, double), and derived types like pointers and arrays.

// Example of basic data types
int age = 30;
double price = 19.99;
char initial = 'A';
bool is_active = true;
int* ptr = &age; // Pointer to an integer

Operators

C++ supports a wide range of operators for arithmetic, comparison, logical operations, bit manipulation, and more. Operator overloading allows custom types to use familiar operators.

// Arithmetic and comparison
int x = 10, y = 5;
int sum = x + y;
bool greater = (x > y);

// Logical operators
bool condition1 = true;
bool condition2 = false;
bool result = condition1 && condition2; // logical AND

Control Flow

Statements like if, else, switch, for, while, and do-while control the execution path of your program.

// For loop example
for (int i = 0; i < 5; ++i) {
    // code to be executed
}

// If-else statement
if (x > 10) {
    // ...
} else {
    // ...
}

Functions

Functions are blocks of code that perform specific tasks. They promote code reusability and modularity. C++ supports function overloading and default arguments.

// Function declaration and definition
int add(int a, int b) {
    return a + b;
}

// Calling a function
int result = add(10, 20);

Classes and Objects (OOP)

Classes are blueprints for creating objects. They encapsulate data members and member functions, enabling object-oriented design principles.

// Simple class definition
class Dog {
public: // Public members
    std::string name;
    int age;

    void bark() {
        std::cout << name << " says Woof!" << std::endl;
    }
};

// Creating an object
Dog myDog;
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark();

Templates

Templates allow you to write generic code that can work with any data type, reducing code duplication. This is fundamental to the Standard Template Library (STL).

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

// Using the template
int i = max(5, 10); // T becomes int
double d = max(3.14, 2.71); // T becomes double

Exception Handling

The try, catch, and throw keywords provide a robust mechanism for handling runtime errors.

try {
    // Code that might throw an exception
    if (some_error) {
        throw std::runtime_error("An error occurred.");
    }
} catch (const std::exception& e) {
    // Handle the exception
    std::cerr << "Caught exception: " << e.what() << std::endl;
}

Runtime Type Information (RTTI)

RTTI allows you to determine the type of an object at runtime, typically used with polymorphic base classes.

// Example using dynamic_cast
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
    // Successfully cast
}

Concurrency

C++11 and later standards provide features for multithreading and concurrency, including threads, mutexes, and atomics.

#include <thread>
#include <vector>

void worker_function() {
    // ... task ...
}

std::vector<std::thread> threads;
for (int i = 0; i < 4; ++i) {
    threads.emplace_back(worker_function);
}

for (auto& t : threads) {
    t.join(); // Wait for threads to finish
}

Standard Library

The C++ Standard Library provides a rich set of pre-written components that you can use in your programs, including:

  • Containers: std::vector, std::list, std::map, std::set, std::string.
  • Algorithms: std::sort, std::find, std::copy, std::transform.
  • Input/Output: std::cin, std::cout, std::fstream.
  • Utilities: std::pair, std::tuple, smart pointers.
  • Concurrency Support: <thread>, <mutex>, <future>.

Explore the Standard Library Reference for detailed information.

Compiler Directives (Preprocessor)

Directives starting with '#' are processed by the preprocessor before compilation. Common directives include:

  • #include: Includes header files.
  • #define: Defines macros.
  • #ifdef, #ifndef, #if, #else, #endif: Conditional compilation.
  • #pragma: Compiler-specific directives.
#define MAX_SIZE 100

#ifdef DEBUG
    // Debug-specific code
#endif

Getting Started with C++

To start programming in C++, you'll need:

  1. A C++ Compiler: Such as GCC (GNU Compiler Collection), Clang, or MSVC (Microsoft Visual C++).
  2. An Integrated Development Environment (IDE): Examples include Visual Studio, VS Code with C++ extensions, CLion, or Code::Blocks.
  3. Learn the Basics: Start with fundamental C++ concepts, variables, data types, control structures, and functions.
  4. Practice: Write small programs and gradually tackle more complex projects.

Refer to the C++ Tutorials for guided learning paths.