C++ Introduction
C++ is a general-purpose, compiled programming language that builds on the C language by adding support for object-oriented programming, generic programming, and fine-grained control over memory and performance.
What Is C++ Used For?
C++ is a popular choice when a program needs to run fast and use system resources efficiently. You’ll find it powering operating systems, web browsers, video game engines, embedded devices, and performance-critical software like databases and trading systems.
Why Learn C++?
- Performance: C++ code is compiled directly to machine code, making it one of the fastest languages available.
- Control: You can manage memory manually, which gives you fine control over how your program uses resources.
- Foundation: Many other languages (like C#, Java, and JavaScript) borrow ideas and syntax from C++, so learning it makes other languages easier to pick up.
- Wide use: C++ is used across many industries, from game development to finance to robotics.
A First C++ Program
Let’s look at a simple C++ program that prints a message to the screen.
#include <iostream>
int main(void) {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Output:
Hello, World!
How It Works
Here’s what each part of the program does:
#include <iostream>tells the compiler to include the input/output stream library, which lets your program read input and print output.int main(void)defines themainfunction. Every C++ program starts running frommain.std::cout << "Hello, World!" << std::endl;sends the text"Hello, World!"to the console, followed by a new line. The<<operator is called the insertion operator, andstd::coutrefers to the standard output stream.return 0;ends themainfunction and tells the operating system the program finished successfully.
The std:: Prefix
cout and endl both belong to the C++ standard library’s std namespace. Writing std::cout tells the compiler exactly where to find cout. Later lessons will show how to avoid repeating std:: using a using statement.
Compiling and Running C++ Code
Unlike some languages, C++ code must be compiled into an executable file before it can run. If you save the program above as hello.cpp, you can compile and run it from a terminal using the GNU C++ compiler:
g++ hello.cpp -o hello
./hello
The first command compiles hello.cpp into an executable named hello. The second command runs it, printing Hello, World! to the screen.
Now that you’ve seen a complete C++ program, the next lesson will walk through setting up your environment and running C++ code on your own computer.
