Skip to main content
Be Bitwise
C++C++ Basics & RAII

Hello, C++!

C++ piles abstractions on top of C (classes, templates, smart pointers, a sprawling standard library) to keep large programs sane. The low-level control is still there when you reach for it.

Your First C++ Program

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

Forget printf — C++ uses streams. std::cout is the standard output stream, and << shovels data into it.

std::endl writes a newline and then flushes the stream. When you only want the newline, '\n' skips the flush.

Key Differences from C

  • #include <iostream> instead of #include <stdio.h> - C++ has its own standard headers (without .h)
  • std:: prefix - the standard library lives in the std namespace
  • Type safety - C++ catches more errors at compile time
  • References and bool are built-in types

Namespaces

The standard library keeps all its names inside one namespace, std, which is why you write std::cout and std::string. A namespace is just a named scope for declarations. Write your own function called count and it won't clash with the library's std::count from <algorithm>, because the two live in different scopes.

You'll meet using namespace std; at the top of plenty of tutorial code. It saves typing by pouring every standard name into the current scope, which is how a harmless-looking local called count or distance ends up fighting the library over overload resolution. Put that line in a header and it does the same to every file that includes it. This track writes std:: out in full. If one name gets tedious, import only that name: using std::cout;.

Compilation

bash
g++ hello.cpp -o hello -std=c++17
./hello

The -std=c++17 flag pins the compiler to the C++17 standard. Modern C++ (C++11 onwards) reshaped how the language gets written in practice.

Key Concept

"C with classes" hasn't described C++ for decades. Modern C++ has its own idioms, patterns, and best practices, and they've drifted a long way from the C lineage. This track teaches modern C++ from the start.

Variables and Auto

C++ added auto for type inference:

cpp
auto x = 42; // int
auto pi = 3.14; // double
auto name = std::string("Alice"); // std::string

auto lets the compiler work out the type from the initialiser. The variable still has exactly one fixed type; you just don't spell it out.

Predict: what type does auto name = "Alice"; give you, and does name.length() compile?

The type is const char *, not std::string. A string literal is an array of const char, and auto deduces the type the way a by-value template parameter would, so the array decays to a pointer to its first character. name.length() is then a compile error, because a pointer has no members. That's why the example above wraps the literal in std::string(...).

std::string

C++ provides a proper string type that manages its own memory:

cpp
#include <string>
std::string greeting = "Hello";
greeting += ", world!";
std::cout << greeting << std::endl; // Hello, world!
std::cout << greeting.length() << std::endl; // 13

No malloc, no strlen, no hand-sized buffers to overrun when you append. std::string grows itself. It won't save you from every mistake, though: greeting[50] is unchecked, just like a C array, while greeting.at(50) checks the index and throws.

Here's the hello program again, plus a C++ take on the GET command from the C track's key-value store capstone. Run it, then change key to something that isn't in the map.

Try itChange key to a missing name, then try greeting[50] in place of greeting.at(50) and notice nothing stops you.
C++ (GCC 9.2.0)

Worked Example: Following a << Chain

Streams look like magic until you unpick one statement. Take this, with x holding 7:

cpp
int x = 7;
std::cout << "x = " << x << '\n';

<< groups left to right, so the compiler reads it as ((std::cout << "x = ") << x) << '\n'. Each << is a function call that returns the same stream it was given:

  1. std::cout << "x = " picks the overload for const char *. It writes the four characters x, space, =, space, and returns a reference to std::cout.
  2. That reference becomes the left operand of << x. Now the overload for int runs. It converts 7 to the character '7', writes it, and returns std::cout again.
  3. << '\n' picks the overload for char and writes a newline.

Output: x = 7 and a newline. The compiler chose a different function at each step from the type of the right-hand operand, which is the type safety printf can't give you: there's no format string to get out of step with the arguments. The flip side is that the type decides everything. std::cout << 'A' + 1 prints 66, because 'A' + 1 is an int, and the int overload prints numbers.

Reading Input

Input runs the other way, through std::cin and >>:

cpp
int age;
std::string first;
std::cin >> age >> first; // types "42 Ada Lovelace": age = 42, first = "Ada"
std::string line;
std::getline(std::cin, line); // reads up to the newline: line = " Lovelace"

>> skips leading whitespace and stops at the next whitespace, so it reads one word or one number at a time. std::getline takes everything up to the newline, removes the newline from the stream and leaves it out of the string. Mixing the two catches people out. After std::cin >> age on its own line, the Enter key's newline is still waiting, and the next getline returns an empty string at once. Calling std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') (from <limits>) first throws the rest of that line away.