Skip to the workspace
Pebellslearn by building
Introduction to C++  ›  Capstone Project

C vs C++

C vs C++ 12 minC and C++ are separate languages with substantial shared syntax. C++ adds features such as classes, templates and automatic resource management, but valid C source is not necessarily valid C++.

cpp / C vs C++

Explore each scene at your own pace.

01 · The rule

The rule

C vs C++

C and C++ are separate languages with substantial shared syntax. C++ adds features such as classes, templates and automatic resource management, but valid C source is not necessarily valid C++.

Identify where C habits conflict with C++ types, initialization and resource ownership.

Rocket Run's sound code came from an old C library, and your new code is C++. Can they live in one project? Mostly yes, because C++ was built on top of C. Knowing exactly where the two differ tells you which old habits to keep and which to upgrade.

The rule

C++ keeps C's core and adds classes, references, templates and a library.

Nearly every C feature exists in C++: the same int, if, for, functions, pointers and structs. What C++ adds:

  • Classes with constructors and destructors, so objects set themselves up and clean up after themselves.
  • References, a safer alternative to many pointer uses.
  • Function overloading: two functions may share a name if their parameters differ.
  • Templates, so one piece of code works for many types.
  • A large standard library: std::string, std::vector, algorithms and more.

The same task in both languages:

/* C */
char name[32];
strcpy(name, "Nova");
int *scores = malloc(10 * sizeof(int));
/* ... */
free(scores);
// C++
std::string name = "Nova";
std::vector<int> scores(10);
// both clean up automatically at the end of the scope

"Mostly compatible" is not "fully compatible". The malloc line above is valid C but an error in C++, because C++ will not silently convert the untyped void* that malloc returns into an int*. C code that uses a C++ keyword such as class or new as a variable name also fails.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.