C vs C++
C++ began as an extension of C and shares its syntax, but it is a separate language with classes, templates and automatic cleanup, and not every valid C program is valid C++.
Distinguish the languages' shared syntax from rules and libraries that differ.
Job adverts often ask for "C/C++", as if it were one language. The two share a history and much of their syntax, yet a program written in the natural style of one looks very different in the other. Knowing where they part ways stops you from mixing their habits.
The rule
C++ grew out of C, but it is a different language, not a bigger C.
In 1979 Bjarne Stroustrup began "C with Classes", renamed C++ in 1983. Today each language has its own ISO standard and its own committee.
C++ adds a great deal on top of C's ideas:
- Classes with member functions, constructors and destructors
- Templates for writing code once for many types
- Exceptions, references, function overloading and namespaces
- A large standard library:
std::vector,std::string,std::map - Destructors that release resources automatically when an object goes out of scope
C stays small: functions, structs, pointers, manual memory management and a compact standard library.
Here is the same idea, "keep 24 hourly readings", in each language. First C, inside a function:
#include <stdlib.h>
double *hourly = malloc(24 * sizeof *hourly); /* ask for 24 slots */
/* ... fill and use them ... */
free(hourly); /* give them back yourself */And the C++ way:
#include <vector>
std::vector<double> hourly(24); // can grow, and frees itselfC is not a strict subset of C++. Some valid C is rejected by a C++ compiler:
int new = 5;is fine in C, butnewis a keyword in C++.- Assigning
malloc's result to adouble *without a cast is fine in C, but C++ demands the cast. - In C a character constant such as
'A'has typeint, sosizeof('A')equalssizeof(int). In C++ it has typechar, so the answer is 1.