Object-Oriented Programming in C++
Classes bundle data and behavior. RAII ties resource lifetime to object scope — C++’s defining OOP pattern.
Class Definition
class Rectangle {
double width_, height_;
public:
Rectangle(double w, double h) : width_(w), height_(h) {}
double area() const { return width_ * height_; }
};
Constructors
class Foo {
int x_;
public:
Foo() : x_(0) {} // default
explicit Foo(int x) : x_(x) {} // prevent implicit conversion
Foo(const Foo&) = default; // copy
Foo(Foo&&) noexcept = default; // move
};
Destructor
class File {
FILE* fp_;
public:
File(const char* path) : fp_(fopen(path, "r")) {}
~File() { if (fp_) fclose(fp_); } // RAII
};
Encapsulation
class BankAccount {
double balance_ = 0;
public:
void deposit(double amount) {
if (amount > 0) balance_ += amount;
}
double balance() const { return balance_; }
};
this Pointer
class Node {
Node* next_;
public:
Node& set_next(Node* n) {
next_ = n;
return *this; // method chaining
}
};
Common Pitfalls
- Ignoring compiler or linter warnings until they become production bugs.
- Skipping error handling on I/O, allocation, and network operations.
- Using outdated patterns when modern idioms exist in your language version.
- Testing only the happy path without edge cases and failure modes.
Best Practices
- Write tests alongside implementation, not after.
- Prefer explicit, readable code over clever one-liners.
- Use the standard library before reaching for third-party dependencies.
- Profile before optimizing; measure after.
- Document public APIs and non-obvious invariants.
Memory and Performance Notes
Virtual destructors are required for polymorphic base classes.
Exercise
Implement a Stack class with push, pop, top, and empty — use std::vector internally.
Hint: Mark methods const when they don’t modify state.
Real-World Application
Production codebases combine these fundamentals with logging, metrics, and error recovery. Study mature open-source projects in this language for idiomatic patterns.
Summary
Master this topic through hands-on practice before advancing to the next section in the learning path.
Debugging Checklist
- Reproduce with minimal input.
- Read error messages completely.
- Binary-search the problem space by commenting out code.
- Compare against a known-good reference implementation.
- Write a regression test once fixed.
Quick Reference
Review the code examples on this page and type them manually — muscle memory accelerates learning.
Further Reading
C++ Core Guidelines, cppreference.com, and Effective Modern C++ by Scott Meyers.
Real-World Context
These patterns appear in Chromium, Unreal Engine, PostgreSQL, and countless production systems.
Additional Examples
Consider how this topic applies in a larger project:
// Break the problem into smaller functions
// Test each function independently
// Integrate incrementally
Working through variations of the examples above builds deeper understanding than reading alone.