Hello World in C++
Your first C++ program - the classic Hello World example with Docker setup
Every C++ journey begins with Hello World. While similar to C’s version, the C++ implementation showcases the language’s more expressive syntax through the iostream library and namespaces.
The Code
Create a file named hello.cpp:
| |
Understanding the Code
#include <iostream>- Includes the input/output stream library, providingstd::coutandstd::endl.int main()- The entry point of every C++ program. Returns an integer to the operating system.std::cout- Character output stream from the standard namespace. The<<operator sends data to the stream.std::endl- End line manipulator that outputs a newline and flushes the stream.return 0- Returns 0 to indicate successful execution (this can be omitted inmain()as C++ automatically returns 0).
Running with Docker
The easiest way to run this without installing a C++ compiler locally:
| |
Running Locally
If you have g++ or clang++ installed:
| |
With Modern C++ Standards
| |
On Windows with MinGW or MSVC:
| |
Expected Output
Hello, World!
Key Concepts
- C++ is compiled - Source code (
.cpp) is compiled to machine code, just like C - iostream vs stdio.h - C++ provides type-safe I/O through streams instead of C’s
printf - Namespaces -
std::prefix indicates the standard namespace, preventing name conflicts - Operator overloading - The
<<operator is overloaded to work with streams - Implicit return - In C++,
main()implicitly returns 0 if no return statement is present
Alternative Approaches
Using namespace directive
| |
While this removes the need for std:: prefixes, it’s generally discouraged in larger programs to avoid namespace pollution.
Using printf (C-style)
C++ is backward compatible with C, so this works too:
| |
However, the iostream approach is preferred in C++ for type safety and extensibility.
Modern C++20 with std::format
| |
C vs C++ Comparison
The equivalent C code would be:
| |
The C++ version offers:
- Type-safe I/O through streams
- No format string vulnerabilities
- Easier to extend with custom types
- Object-oriented stream manipulation
Next Steps
Continue to Variables and Data Types to learn about C++’s rich type system, including modern features like auto and type inference.