C++ vs C
C++ started as an extension of C, and most C code still compiles in C++. But the two languages are now different, and C++ has much more.
| Point | C | C++ |
|---|---|---|
| Style | Procedural | Procedural, object oriented and generic |
| Classes and objects | No (only struct with data) | Yes |
| Function overloading | No | Yes |
| References | No (only pointers) | Yes (int&) |
| Templates | No | Yes |
| Namespaces | No | Yes |
| Exceptions | No | Yes (try and catch) |
| Strings | char arrays | std::string and std::string_view |
| Containers | You write them | STL: vector, map, set and more |
| Memory | malloc and free | new, delete, smart pointers, RAII |
| Input and output | printf and scanf | std::cout, std::cin, std::print |
| Boolean | Needs stdbool.h | bool is built in |
The same program in both
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 9, 1}; // C++ container, grows by itself
std::sort(numbers.begin(), numbers.end()); // ready algorithm
for (int n : numbers) {
std::cout << n << ' ';
}
std::cout << '\n';
}
Output
1 2 5 9
In C you would write the array, the size and the sort function by yourself (or use qsort).
Some C code is not valid C++
#include <stdlib.h>
int main() {
int* p = malloc(4 * sizeof(int)); // fine in C, an error in C++ (no automatic void* conversion)
free(p);
}
Output
Bad.cpp: In function 'int main()':
Bad.cpp:4:20: error: invalid conversion from 'void*' to 'int*' [-fpermissive]
4 | int* p = malloc(4 * sizeof(int)); // fine in C, an error in C++ (no automatic void* conversion)
| ~~~~~~^~~~~~~~~~~~~~~~~
| |
| void*
Note:
If you know C, C++ is the natural next step. See the C Tutorial of this website. Next: C++ Installation and Setup.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |