C++ in Detail
C++
Introduction
C++ is a statically typed, compiled programming language.
Known for its use in software infrastructure.
Created in 1979 by Bjarne Stroustrup at AT&T Bell Labs.
Inspired by Simula but needed C's performance.
Originally named "C with Classes."
Superset of C: virtually any C program is a valid C++ program.
Adds zero-overhead abstractions like object-oriented patterns (polymorphism, encapsulation, inheritance).
Used in systems with constrained memory demands:
Unreal Engine (AAA video games)
Adobe After Effects
Databases (MySQL, MongoDB)
Embedded systems (SmartToaster display)
Low-level infrastructure (language compilers, virtual machines)
Combines low-level memory and hardware control of C with high-level abstractions.
C++ makes it harder to shoot yourself in the foot, but when you do, it'll blow your whole leg off.
Getting Started
Install a C++ compiler (e.g., GCC, Clang).
Create a file with the
.cppextension.Include
iostreamfrom the standard library for input/output.Code execution starts from the
mainfunction.
Basic Syntax
Printing "Hello, World!"
#include <iostream> int main() { std::cout << "Hello, World!"; return 0; }Eliminating
stdusing namespace:#include <iostream> using namespace std; int main() { cout << "Hello, World!"; return 0; }String variables:
As an array of characters:
char my_string[] = "Hello";Using the
stringtype (include<string>):#include <string> string my_string = "Hello";
Object-Oriented Programming
Classes: Blueprints for objects.
Attributes and methods are defined inside a class.
Access specifiers:
private(default)public
Defining methods outside the class definition:
class MyClass { public: void myMethod(); }; void MyClass::myMethod() { // Method implementation }Method overloading: Defining methods multiple times with different parameters (a form of polymorphism).
Constructors and destructors:
Run code when an object is created or destroyed.
class MyClass { public: MyClass() { // Constructor // Initialization code } ~MyClass() { // Destructor // Cleanup code } };
Inheritance: Sharing logic throughout a program more efficiently.
class BaseClass { public: void baseMethod() {} }; class DerivedClass : public BaseClass {};Instantiating an object:
MyClass myObject(parameters);
Memory Management
Manual memory management with pointers and references.
Smart pointers (e.g.,
unique_ptr):Easier and safer memory management.
Ensures only one object can be allocated to memory.
Compilation
Using a tool like Clang++ to compile the code.
clang++ my_code.cpp -o my_program