C++ is a superset of C that introduces Object-Oriented Programming (OOP) and the Standard Template Library (STL). It offers both low-level memory control (like C) and high-level abstractions.
Instead of <stdio.h> and printf(), C++ uses <iostream> and streams (std::cout).
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}std::cout: Character Output stream.<<: Stream insertion operator.std::endl: End line (also flushes the buffer).
Namespaces prevent name conflicts. You can avoid typing std:: everywhere by using:
using namespace std;(Note: Avoid using this in header files to prevent global namespace pollution).
C++ introduces references (&), which act as safe aliases to variables, avoiding pointer arithmetic.
int x = 10;
int& ref = x; // ref is now an alias for x
ref = 20; // x is now 20class Person {
private:
std::string name;
public:
// Constructor
Person(std::string n) : name(n) {}
// Method
void greet() {
std::cout << "Hi, I am " << name << std::endl;
}
};
int main() {
Person p("Alice");
p.greet();
}Instead of malloc() and free(), C++ uses new and delete.
int* p = new int(10); // Allocate integer initialized to 10
delete p; // Free memory
int* arr = new int[5]; // Allocate array
delete[] arr; // Free array(Modern C++ discourages raw new/delete in favor of Smart Pointers).