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.

PointCC++
StyleProceduralProcedural, object oriented and generic
Classes and objectsNo (only struct with data)Yes
Function overloadingNoYes
ReferencesNo (only pointers)Yes (int&)
TemplatesNoYes
NamespacesNoYes
ExceptionsNoYes (try and catch)
Stringschar arraysstd::string and std::string_view
ContainersYou write themSTL: vector, map, set and more
Memorymalloc and freenew, delete, smart pointers, RAII
Input and outputprintf and scanfstd::cout, std::cin, std::print
BooleanNeeds stdbool.hbool 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.