C++: a quick overview

See the dedicated pages for details.

Basics of a Class

A class in C++ is a blueprint for creating objects. It encapsulates data and functions that operate on the data. Syntax:

class ClassName {
  // Access specifiers
  // Data members
  // Member functions
};

Class Constructor

A constructor initializes objects of a class. It has the same name as the class:

ClassName() {
  // Initialization code
}

Class Constructor Initializer List

Use an initializer list to initialize class members before the constructor body executes:

ClassName() : member1(value1), member2(value2) {
// Constructor body
}

Class Destructor and Virtual Destructor

A destructor cleans up resources. Use a virtual destructor in base classes to ensure derived class destructors are called:

virtual ~ClassName() {
// Cleanup code
}

Class Assignment Operator

Overload the assignment operator to assign values from one object to another:

ClassName& operator=(const ClassName& other) {
// Assignment code
return *this;
}

Class Access Specifiers

Access specifiers define the scope of class members:

Class Friendship

A friend function or class can access private and protected members of another class:

class ClassName {
friend void FriendFunction();
};

Class Relationship

Inheritance

Derive a class from a base class:

class Derived : public Base {
  // Additional members
};

Polymorphism

Achieve polymorphism using virtual functions:

virtual void FunctionName() {
  // Code
}

Const Member Function

A const member function does not modify the object:

void FunctionName() const {
// Function code
}

Smart Pointers

Templates

Function Template: Define functions with generic types.

template <typename T>
T FunctionName(T param) {
  // Code
}

Class Template: Define classes with generic types.

template <typename T>
class ClassName {
  T member;
};

Variable Template: Define variables with generic types.

template <typename T>
constexpr T pi = T(3.1415926535897932385);

Template Specification

Provide specific implementation for certain types:

template <>
class ClassName {
  // Specialized code for int
};

Type Casting

Pass by Value, Pointer, or Reference