Bytebook Compiler

From C to C++

C++ Introduction

Where C++ came from, what it adds to C, your first program with iostream and namespaces, and how to compile it.

3 min read2 runnable examples4-question quiz

C++ was created by Bjarne Stroustrup at Bell Labs, starting in 1979 as "C with Classes". It keeps almost everything from C — the speed, the pointers, the control over memory — and adds tools for organising large programs: classes and objects, references, function overloading, templates, exceptions and a huge Standard Template Library (STL).

C++ powers game engines (Unreal), browsers (Chrome, Firefox), databases, trading systems, compilers and most performance-critical software you use.

Your first C++ program

C++
#include <iostream>

int main() {
    std::cout << "Hello, C++!" << std::endl;
    std::cout << "2 + 3 = " << 2 + 3 << "\n";
    return 0;
}
Output
Hello, C++!
2 + 3 = 5
Line Meaning
#include <iostream> the input/output stream library (no .h)
std::cout the standard character output stream — the screen
<< the insertion operator: sends the value on its right into the stream
std::endl ends the line and flushes the output; "\n" just ends the line
std:: everything in the standard library lives in the namespace std

Namespaces and using

A namespace groups names to avoid clashes — two libraries can both have a sort function if they live in different namespaces. Writing std:: everywhere is precise; using namespace std; lets you drop the prefix:

C++
#include <iostream>
using namespace std;

namespace physics { double g = 9.8; }
namespace games   { double g = 1.6; }     // same name, different namespace

int main() {
    cout << "Earth gravity: " << physics::g << endl;
    cout << "Moon gravity in our game: " << games::g << endl;
    return 0;
}
Output
Earth gravity: 9.8
Moon gravity in our game: 1.6

Compiling

Terminal
g++ hello.cpp -o hello      # g++ is the C++ compiler from GCC
./hello
g++ -std=c++17 -Wall hello.cpp -o hello   # pick a standard and turn on warnings

What C++ adds to C

Feature C C++
Programming style procedural procedural and object-oriented and generic
Input/output printf, scanf cout, cin (type-safe)
Data + functions together no classes
References no int &r = x;
Function overloading no yes
Default arguments no yes
Dynamic memory malloc / free new / delete
Strings char arrays std::string
Error handling return codes exceptions
Generic code macros, void * templates
Ready-made data structures none STL: vector, map, set, …

Almost any valid C program is also a valid C++ program, so everything from CSE 101 still applies.

Test yourself

4 questions · pick an answer to check it instantly

  1. 1

    Who created C++?

  2. 2

    What does << do in cout << x;?

  3. 3

    Why does C++ have namespaces?

  4. 4

    Which of these is not a C++ feature that C lacks?