C++ Overview
C++ is a general-purpose programming language created as an extension of the C programming language with object-oriented features. It is used in performance-critical applications where efficiency and flexibility are important.
Key Features
- Object-Oriented: Supports classes, inheritance, polymorphism.
- Template Metaprogramming: Powerful generic programming features.
- Low-Level Memory Manipulation: Direct memory access via pointers.
- Standard Template Library (STL): Rich collection of algorithms and containers.
- Performance: Compiles to highly optimized machine code.
- Portability: Can be compiled for many platforms.
- Backward Compatibility: Mostly compatible with C code.
Common Use Cases
Game Development
Used in game engines like Unreal Engine.
System Software
Operating systems, device drivers, embedded systems.
High-Frequency Trading
Low-latency financial applications.
Scientific Computing
Performance-intensive numerical computations.
Example Code
// Modern C++ example demonstrating features
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Class with constructor and methods
class Rectangle {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const { return width * height; }
double perimeter() const { return 2 * (width + height); }
};
// Template function
template <typename T>
T max_value(const vector<T>& v) {
return *max_element(v.begin(), v.end());
}
int main() {
// Smart pointer and lambda
auto rect = make_unique<Rectangle>(3.0, 4.0);
cout << "Area: " << rect->area() << endl;
// Range-based for loop
vector<int> numbers = {3, 1, 4, 1, 5, 9};
cout << "Numbers: ";
for (auto n : numbers) {
cout << n << " ";
}
cout << endl;
// Algorithm and lambda
cout << "Max: " << max_value(numbers) << endl;
auto is_even = [](int n) { return n % 2 == 0; };
cout << "First even: " << *find_if(numbers.begin(), numbers.end(), is_even) << endl;
return 0;
}