C++ was created by Bjarne Stroustrup in 1979 as “C with Classes.” It aimed to combine the speed of C with object-oriented programming concepts. Over the years, standards like C++98, C++03, C++11, C++14, C++17, and C++20 have added features like smart pointers, auto keyword, range-based loops, modules, coroutines, and concepts.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++ World!" << endl;
return 0;
}
This demonstrates the classic “Hello World” and highlights headers, namespaces, and the main function.
class Animal {
public:
string name;
void speak() { cout << name << " makes a sound." << endl; }
};
int main() {
Animal cat;
cat.name = "Whiskers";
cat.speak();
}
Shows class creation, public members, and methods in C++.
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << add(5, 10) << endl; // ints
cout << add(2.5, 4.1) << endl; // doubles
}
Templates allow functions or classes to work with any data type.
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4};
nums.push_back(5);
for(int n : nums) cout << n << " ";
}
STL provides ready-to-use containers and algorithms.
# Python
numbers = [1,2,3,4]
squared = [n**2 for n in numbers]
print(squared)
# C++
#include <iostream>
int main() {
int numbers[] = {1,2,3,4};
for(int n : numbers) cout << n*n << " ";
return 0;
}
C++ is faster and provides memory control, Python is simpler and more readable.
// Java
String name = "C++ vs Java";
System.out.println("Hello, " + name);
// C++
#include <iostream>
#include <string>
int main() {
std::string name = "C++ vs Java";
std::cout << "Hello, " << name << std::endl;
}
Rust provides memory safety and modern syntax, C++ offers mature libraries and maximum control.
Even the most serious coders deserve a chuckle. 😄