Introduction to C++

A tour of what C++ is, where it came from, and why a language that lets you touch raw memory can also give you templates, classes, and a huge standard library.

C++ is a general-purpose, compiled, statically typed, multi-paradigm programming language designed to provide both high-level programming features and low-level control over system resources. C++ evolved from the C programming language and added powerful features such as classes, objects, inheritance, polymorphism, templates, exception handling, references, and generic programming. Today, C++ is used in areas where performance, control, efficiency, and flexibility are important.

What is C++?

C++ is a programming language that allows developers to build software ranging from small applications to large, performance-critical systems. It supports multiple programming styles: procedural programming, object-oriented programming, generic programming, functional-style programming, and low-level/system programming.

A minimal C++ program that prints a greeting to standard output.

This program displays: Hello, C++! Although the syntax looks similar to C, C++ provides many additional language features.

#include <iostream>
int main()
{
    std::cout << "Hello, C++!";
    return 0;
}

Why Was C++ Created?

C++ was created by Bjarne Stroustrup at Bell Labs. The initial goal was to extend C with features that made it easier to design and manage large software systems, particularly through classes and object-oriented programming.

The language originally evolved through a series of extensions to C and was initially associated with the name "C with Classes." Later, the language was named C++. The ++ comes from the C increment operator.

The increment operator that inspired the name "C++".

Conceptually, the name suggests an evolution or increment of C.

Brief History of C++

A simplified history looks like this:

Some important versions are:

C++ continues to evolve through new standards.

C
│
├── C with Classes
│
├── C++
│
├── C++98
│
├── C++03
│
├── C++11
│
├── C++14
│
├── C++17
│
├── C++20
│
└── C++23
Version   Important additions
C++98     First standardized C++
C++03     Corrections and improvements
C++11     Major modernization: auto, lambdas, move semantics, smart pointers, nullptr, etc.
C++14     Improvements to C++11
C++17     Structured bindings, if constexpr, std::optional, std::variant, etc.
C++20     Concepts, ranges, coroutines, modules, and many other features
C++23     Further library and language improvements

C++ Is a General-Purpose Language

C++ is not designed for only one type of application. It can be used to develop desktop applications, game engines, browsers, operating-system components, compilers, high-performance applications, financial systems, robotics software, real-time software, scientific applications, and large-scale software systems.

C++ Is a Compiled Language

C++ programs are normally compiled before execution.

A program that must be compiled before it can run.

The source code is processed by a compiler and eventually produces executable code suitable for the target platform. A simplified flow is:

The detailed compilation and build process is covered separately.

#include <iostream>
int main()
{
    std::cout << "Hello";
}
C++ Source Code
       ↓
Preprocessing
       ↓
Compilation
       ↓
Object Code
       ↓
Linking
       ↓
Executable
       ↓
Execution

Statically Typed Language

C++ is statically typed. This means the type of an object is determined as part of the program's type system and generally known during compilation.

Three objects with three different, compile-time-known types.

Here: age is an int, salary is a double, grade is a char. The compiler uses type information to detect many programming errors before the program runs.

An invalid initialization the compiler will reject.

This is not a valid initialization because a string literal cannot be used as an int.

int age = 25;
double salary = 50000.50;
char grade = 'A';
int age = "twenty";

Object-Oriented Programming

One of the most important features associated with C++ is object-oriented programming (OOP). C++ allows programmers to represent entities using classes and objects.

A simple class with one member function.

Creating an object of the Car class.

Important OOP concepts in C++ include classes, objects, encapsulation, abstraction, inheritance, and polymorphism. These concepts are covered separately in the C++ curriculum.

class Car
{
public:
    void start()
    {
        // Start the car
    }
};
Car car1;

Multi-Paradigm Language

C++ is not limited to object-oriented programming. It supports multiple programming paradigms.

Procedural style: a free function.

Object-oriented style: the same operation as a member function.

Generic programming: a function template that works for any type T.

Functional-style programming: C++ also supports concepts such as lambda expressions, higher-order functions, function objects, and algorithms. Therefore, C++ is best described as a multi-paradigm language.

int add(int a, int b)
{
    return a + b;
}
class Calculator
{
public:
    int add(int a, int b)
    {
        return a + b;
    }
};
template <typename T>
T add(T a, T b)
{
    return a + b;
}

C++ and Low-Level Programming

C++ provides abstractions while still allowing relatively direct interaction with system resources. For example, C++ provides pointers, references, manual dynamic allocation, memory-address manipulation, bitwise operations, and low-level object representation control.

At the same time, it provides higher-level facilities such as std::string, std::vector, std::unique_ptr, and std::optional. This combination is one of the major strengths of C++.

C++ and Performance

C++ is widely used when performance is important. One reason is that C++ allows programmers to control many aspects of how objects and resources are represented and used.

A simple operation with no hidden runtime machinery.

C++ does not require a virtual machine or garbage collector for ordinary execution. However, this does not mean every C++ program is automatically fast. Performance depends on algorithms, data access patterns, memory usage, compiler optimizations, object lifetime, allocations, I/O, concurrency, and program design. C++ provides the tools for high performance; the programmer still has to use them correctly.

int calculate(int a, int b)
{
    return a + b;
}

C++ Is Not Simply "C with Classes"

C++ originated from C, but modern C++ is much more than C plus classes. C++ provides language features such as class, template, namespace, auto, nullptr, constexpr, concept, and lambda, and standard-library facilities such as std::vector, std::string, std::unique_ptr, std::optional, and std::variant.

Modern C++ programming generally emphasizes abstraction, type safety, resource management, generic programming, and reusable components rather than simply writing C code with classes.

C++ vs C — Basic Difference

C and C++ share many fundamental concepts and syntax, but they have different capabilities.

C++ also maintains substantial compatibility with C, but C and C++ are separate languages, and valid C code is not necessarily valid C++ code.

Feature               C                        C++
Programming style     Primarily procedural     Multi-paradigm
Classes               No                       Yes
Objects               No native class objects  Yes
Inheritance           No                       Yes
Polymorphism          Limited/manual            Built-in language support
Function overloading  No                       Yes
Templates             No                       Yes
References            No                       Yes
Exceptions            No                       Yes
Namespaces            No                       Yes
RAII                  No                       Yes
Smart pointers        No, standard C lib only  Yes, standard C++ feature
Standard containers   Limited C library        Extensive C++ library

First C++ Program

A complete, minimal C++ program.

int main() is the function where program execution begins for a hosted C++ program. Its return type is int.

{ } — The braces define the body of the main function.

std::cout represents the standard output stream. The std:: indicates that cout belongs to the std namespace.

The << operator is used here to insert data into the output stream, as in: std::cout << "Hello, World!";

return 0 returns the value 0 from main, conventionally indicating successful program termination. For main, reaching the closing } also results in returning 0.

#include <iostream>
int main()
{
    std::cout << "Hello, World!";
    return 0;
}

Basic C++ Terminology

Understanding common terminology makes later C++ topics much easier.

Source Code — The human-readable C++ program written by the programmer. Example: int x = 10;

Compiler — A tool that translates C++ source code into lower-level code as part of producing an executable program.

Object — an instance of a type that has storage and a lifetime.

Here, age is an object of type int.

Class — a user-defined type that can contain data members and member functions.

Object of a Class — an instance of a class.

Function — a named unit of executable behavior.

Namespace — a named scope used to organize declarations and avoid name conflicts.

Standard Library — The C++ standard library provides reusable facilities such as strings, containers, algorithms, utilities, streams, smart pointers, and more.

int age = 25;
class Student
{
    // members
};
Student student1;
int add(int a, int b)
{
    return a + b;
}
namespace Math
{
    int value = 10;
}

Where Is C++ Used?

C++ is used in many performance-sensitive and large-scale software systems.

Game Development — C++ is widely used for game engines, rendering systems, physics, audio, and gameplay systems.

Operating Systems & System Software — C++ can be used for system components, runtime software, development tools, compilers, and browsers. Major browser software contains substantial amounts of C++.

Desktop Applications — C++ is used for applications where performance and native platform integration are important.

High-Performance Computing — C++ is used in scientific computing, simulations, numerical software, and large-scale computation.

Robotics — C++ is commonly used where performance and hardware/software integration are important.

Financial Software — C++ is used in systems where predictable and efficient execution is important.

Advantages of C++

1. High Performance — C++ can produce highly efficient native applications.

2. Abstraction — C++ allows high-level abstractions without necessarily requiring a high runtime overhead.

3. Object-Oriented Programming — Classes, inheritance, polymorphism, and encapsulation help organize large applications.

4. Generic Programming — Templates allow reusable code that works with different types.

5. Strong Type System — The type system allows the compiler to detect many programming errors.

6. Resource Management — Features such as RAII and smart pointers provide powerful mechanisms for managing resources.

7. Large Standard Library — C++ provides a large collection of standardized language and library facilities.

8. Portability — C++ programs can often be compiled for different platforms with appropriate platform-specific adjustments.

Limitations and Challenges of C++

C++ is powerful, but that power also introduces complexity.

1. Large Language — Modern C++ contains many language features and rules.

2. Manual Resource Management Is Possible — C++ allows manual management of resources, which can lead to problems if used incorrectly.

A manually managed resource that must eventually be released.

Modern C++ generally encourages safer ownership mechanisms such as RAII and smart pointers.

3. Undefined Behavior — Incorrect C++ programs can invoke undefined behavior. Examples include accessing an object outside its lifetime, invalid memory access, certain invalid pointer operations, and signed integer overflow.

4. Compilation Complexity — Large C++ projects can involve complicated dependencies, templates, headers, and build systems.

5. Multiple Ways to Solve the Same Problem — C++ often provides several possible approaches. This gives flexibility but also means programmers need to understand which approach is appropriate.

int* p = new int(10);
// Resource must eventually be released
delete p;

Modern C++ Philosophy

Modern C++ emphasizes writing code that is type-safe, resource-safe, expressive, maintainable, efficient, and reusable.

Manually managing a dynamically allocated object.

The modern equivalent using a smart pointer.

The important idea is that resource ownership should be represented clearly in the program's types and object lifetime. This concept is developed later through RAII and smart pointers.

int* value = new int(10);
// use value
delete value;
auto value = std::make_unique<int>(10);

C++ Standard and Compilers

C++ is standardized by the ISO C++ standardization process. The standard defines the language and standard library behavior. Different compilers implement the standard.

Common C++ compilers include GCC, Clang, Microsoft Visual C++ (MSVC), and Intel C++ compiler/toolchains. A compiler may support different language standards such as C++11, C++14, C++17, C++20, and C++23.

The exact compiler command depends on the development environment.

g++ -std=c++20 main.cpp -o main

C++ Program Execution — Basic Mental Model

At a high level:

The source program that this pipeline turns into a running executable.

The compiler and linker transform the source program into an executable form that the operating system can load and run. The detailed mechanics belong to the separate C++ Compilation & Build Process topic.

What does it mean that C++ is a "statically typed" language, and how does that affect a line like int age = "twenty";?

Statically typed means the type of every object is fixed and generally known at compile time. Because age is declared int, initializing it from a string literal is a type mismatch the compiler rejects before the program ever runs.

Name three programming paradigms C++ supports and give one language feature associated with each.

Procedural (plain functions like int add(int,int)), object-oriented (classes with member functions), generic (function/class templates like template<typename T>), and functional-style (lambda expressions, higher-order functions) are all supported — which is why C++ is called multi-paradigm.

Why is describing modern C++ as just "C with classes" considered inaccurate?

Modern C++ adds far more than classes on top of C: templates, namespaces, auto, nullptr, constexpr, concepts, lambdas, and a large standard library (std::vector, std::unique_ptr, std::optional, etc.). It emphasizes abstraction, type safety, resource management, and generic programming rather than just object syntax bolted onto C.

In what sense does C++ give programmers low-level control while also offering high-level abstractions?

C++ exposes low-level facilities like pointers, references, manual dynamic allocation, and bitwise operations, while also providing higher-level types such as std::string, std::vector, and std::unique_ptr — letting a programmer choose the right level of abstraction for the problem.

Why doesn't the absence of a virtual machine or garbage collector automatically make a C++ program fast?

Not needing a VM or GC removes certain runtime overheads, but real performance still depends on algorithms, data access patterns, memory usage, compiler optimizations, object lifetime, allocations, I/O, concurrency, and overall program design. C++ provides the tools; the programmer still has to use them well.

Why does this line fail to compile in standard C++?

C++'s static type system does not allow a string literal to initialize an int object; the compiler detects this type mismatch during compilation rather than letting it fail at runtime.

Write a minimal, complete C++ program that includes <iostream>, prints "C++ Rocks!" to standard output, and explicitly returns 0 from main.

The program includes iostream for std::cout, uses main() as its entry point, sends the string literal to standard output with <<, and returns 0 to indicate successful termination.

What paradigm does this function demonstrate, and why can the same code work for both int and double arguments?

This is generic programming via a function template. T is a placeholder type that the compiler substitutes with the actual argument type (int, double, etc.) at each call site, so one definition works for many types.

Write a small C++ program with a class named Greeter that has one member function sayHello() printing "Hello!"; create a Greeter object in main and call the function.

Greeter is a class with a public member function sayHello(). greeter1 is an object of that class, and greeter1.sayHello() invokes the member function on that object, printing "Hello!".

C++ Source Code
               │
               ▼
        Preprocessing
               │
               ▼
          Compilation
               │
               ▼
          Object Code
               │
               ▼
            Linking
               │
               ▼
          Executable
               │
               ▼
           Program Run
#include <iostream>
int main()
{
    std::cout << "Hello";
}
int number = "hello";
template <typename T>
T add(T a, T b)
{
    return a + b;
}