Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 171 ยท Object-Oriented Programming

Object-Oriented Programming in C++

An overview of object-oriented programming in C++ - classes and objects, encapsulation, inheritance, polymorphism and abstraction, and how OOP fits C++'s multi-paradigm style.

So far you've written programs as data plus free functions: a std::vector<double> of balances here, a deposit function there. That works well for small programs, but as code grows, nothing stops some distant function from setting a balance to a negative number or forgetting to record a transaction. Object-oriented programming (OOP) attacks this by bundling data together with the operations allowed on it, and by hiding the data so only those operations can change it.

C++ began life in 1979 as "C with Classes", and classes are still at its heart. But C++ never forces OOP on you: it is a multi-paradigm language that mixes procedural, object-oriented, generic and functional styles in one program. This lesson gives you the big picture before the following lessons dive into each feature. You'll meet the four classic pillars of OOP (encapsulation, abstraction, inheritance and polymorphism), see each one in running C++ code, and learn when a class is the right tool and when it isn't.

Classes and objects

A class is a user-defined type that describes what data an object holds (its member variables, or data members) and what it can do (its member functions, also called methods). An object is a value of that type, a concrete instance with its own copy of the data. std::string and std::vector are classes from the standard library; every string you've created was an object.

Here is the problem from the introduction solved with a class. Compare it with what a plain struct or loose variables would allow.

C++ A class that protects its data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every public operation keeps the account valid: the balance can never go negative, because the only code that can change it checks first. Uncomment the last line and the compiler refuses: balance_cents_ is private. Classes and Objects covers the syntax in detail and Constructors and Member Initializer Lists explains the : owner_{...} part.

The four pillars

OOP is usually described with four ideas. They overlap, and C++ implements each with specific language features.

Pillar The idea C++ features
Encapsulation Bundle data with its operations and hide the data class, private/public, member functions
Abstraction Expose what an object does, hide how Small public interfaces, abstract classes
Inheritance Build a new class from an existing one class Derived : public Base
Polymorphism One interface, many implementations, chosen at run time virtual functions, override

Encapsulation

Encapsulation means an object owns its data and is the only one allowed to modify it directly. The rest of the program goes through member functions. That gives you a single place to enforce rules (an account balance never goes negative, a date is always a real date), which the class guarantees as its invariants. If a bug breaks an invariant, you know it must be inside the class. You'll design invariants properly in Access Specifiers and Encapsulation.

Abstraction

Abstraction means users of a class only need to know what it does, not how. You've relied on this constantly: std::vector::push_back grows the buffer when needed, and you never had to know the growth factor. A good abstraction lets you change the implementation (say, store a balance in a database instead of a member variable) without touching any code that uses the class.

Inheritance

Inheritance creates a new class (the derived class) from an existing one (the base class). The derived class gets all of the base's members and can add more. It models an is-a relationship: a savings account is a bank account with interest added.

C++ Inheritance: a derived class reuses and extends a base

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Manager didn't rewrite name() or yearly_pay(); it inherited them. And because a Manager is an Employee, print_badge accepts it without any changes. Inheritance explains constructor order, protected and the rules for hiding members.

Inheritance is the most overused OOP feature. Use it for genuine is-a relationships where you need polymorphism. If you only want to reuse code, a member variable (composition: a car has an engine) is almost always simpler and more flexible.

Polymorphism

Polymorphism ("many forms") lets code work with a base class while each derived class supplies its own behavior. In C++ you opt in per function with the keyword virtual; the derived class marks its version with override. A call through a base-class reference or pointer then runs the derived class's version, decided at run time (dynamic dispatch).

An abstract class has at least one pure virtual function (= 0) and can't be instantiated itself. It serves as an interface: a list of operations every derived class must provide. That is abstraction and polymorphism working together.

C++ Polymorphism through a virtual interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The loop knows nothing about circles or rectangles; it only knows Shape. Adding a Triangle later means writing one new class, with no change to the loop. That open for extension quality is the main payoff of polymorphism. The objects are stored through std::unique_ptr<Shape> because a vector of plain Shape values can't hold different derived types, as Virtual Functions and Polymorphism explains together with the mandatory virtual destructor. Abstract Classes and Interfaces builds on this design.

How classes relate: association, aggregation and composition

Real programs have many classes, and the interesting design question is how they are connected. Inheritance ("is-a") is only one connection. The others are "has-a" or "uses-a" relationships, and C++ expresses them through how an object holds another one.

  • Association: one class knows about another and uses it, but neither owns the other. A Coach reviews a Team; both exist independently. In code: a reference or pointer, or a parameter of a member function.
  • Aggregation (weak ownership): a whole has parts, but the parts can outlive the whole and may be shared. A Team has Players; delete the team and the players still exist. In code: a non-owning pointer or reference, or std::shared_ptr/std::weak_ptr when sharing.
  • Composition (strong ownership): the whole owns its parts, and they live and die with it. A Car has an Engine. In code: a plain data member (or a std::unique_ptr member when the part must live on the heap).
C++ Association, aggregation and composition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output shows that the engine is destroyed exactly when its car is, while the players survive their team and are only destroyed at the end of main. Aggregation with raw pointers is safe only if the parts really do outlive the whole; if you can't guarantee that, use std::shared_ptr (see Shared and Weak Pointers). When unsure, prefer composition: members are the simplest, fastest and safest way to build objects out of objects.

Limitations of OOP

OOP is a tool, not a religion, and it has costs that explain why C++ also offers templates and free functions:

  • A steeper learning curve. You need classes, access control, constructors, virtual functions and lifetime rules before you can read a typical code base.
  • More code and indirection. Small problems can balloon into class hierarchies spread over many files; a free function is often shorter.
  • Run-time cost of virtual dispatch. A virtual call is an indirect call the optimizer often can't inline, and each polymorphic object carries a hidden pointer.
  • Deep hierarchies are brittle. A change in a base class ripples into every derived class (the "fragile base class" problem). Prefer shallow hierarchies and composition.
  • Not every problem is object-shaped. Numeric kernels, data pipelines and text processing are often clearer as plain functions over containers.
  • Encapsulation must be designed. A class that exposes a getter and setter for every member hides nothing; the invariants you wanted to protect are still open to everyone.

On the positive side, the same ideas give you maintainability (changes stay inside one class), flexibility (new types plug into old code), reuse (one tested class used in many places) and the DRY principle (each rule written once, in the class that owns it).

C++ is multi-paradigm

Java and C# put everything inside classes. C++ doesn't. Free functions, templates and lambdas are first-class tools, and idiomatic C++ picks the best one for each job:

  • Procedural: free functions working on data. std::sqrt, std::ranges::sort and most of <algorithm> are free functions.
  • Object-oriented: classes with invariants and, where you need run-time flexibility, virtual functions.
  • Generic: templates and concepts that work for any type with the right operations. std::vector<T> and std::ranges::sort work on types that didn't exist when they were written, and without any virtual calls.
  • Functional: lambdas, immutable values and algorithms that transform ranges.

The next example solves the "print each shape's area" task generically: no base class and no virtual functions, just any type that has area() and name(). You'll learn the template syntax in Function Templates and the requires constraint in Concepts and Constraints.

C++ The same idea without inheritance: generic code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Both versions print areas, but they make different trade-offs. The virtual version decides at run time, so one vector can hold mixed shapes chosen while the program runs (from a file, say). The template version decides at compile time: each call is resolved and can be inlined, with no pointers or heap allocation, but you can't put a Square and a Triangle in the same std::vector. Experienced C++ programmers use both, and also std::variant for a fixed set of alternatives, which you'll see in std::optional, std::variant, std::any and std::expected.

When to write a class

A useful test: does this data have rules? If some combinations of member values are invalid, write a class with private data and member functions that keep it valid. If any combination is fine, a simple struct with public members is clearer.

Situation Good choice
A bundle of values with no rules (a 2D point, an RGB color) struct with public members (Structs, Aggregates and Unions)
Data with invariants (an account, a date, a fraction in lowest terms) class with private members
A type that owns a resource (a file, a lock, a socket) class with a destructor, see Destructors and RAII
Several types used interchangeably at run time Abstract base class with virtual functions
One algorithm for many types, known at compile time Template, constrained with a concept
A single operation with no state A free function

C++'s classes are also zero-overhead: a class with a private double and some inline member functions compiles to the same machine code as working with a bare double. Encapsulation in C++ costs nothing at run time; only virtual functions add a small cost (one indirect call and one hidden pointer per object, as Memory Layout showed).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main purpose of making a class's data members private?

    Private data can only be modified by member functions, so the class has one place to check every change and keep its data valid. It has no effect on speed, copying or visibility across files.
  2. 2. Given class Manager : public Employee, which statement is true?

    Public inheritance models is-a, so a Manager can be used wherever an Employee is expected. The reverse isn't true, because a plain Employee has no team size.
  3. 3. In the Shape example, why does the loop print the right area for each object even though it only sees Shape references?

    Marking area() virtual in the base class enables dynamic dispatch. Each call through a Shape reference or pointer runs the override of the object's actual type.
  4. 4. You want a simple type that holds red, green and blue values, where every combination is valid. What is the most fitting choice?

    With no invariants to protect, private data and getters add ceremony without safety. A plain aggregate struct is clearer.

Summary

  • A class bundles data members and member functions into a new type; an object is an instance with its own data.
  • Encapsulation hides data behind member functions so the class can enforce its invariants; abstraction exposes what an object does, not how.
  • Inheritance builds a derived class from a base class for is-a relationships; prefer composition for plain code reuse.
  • Polymorphism uses virtual functions and override so code written against a base class runs each derived class's behavior; abstract classes with pure virtual functions act as interfaces.
  • C++ is multi-paradigm: free functions, templates, lambdas and classes are all idiomatic. Virtual functions decide at run time; templates decide at compile time.
  • Write a class when data has rules or owns a resource; use a plain struct when any combination of values is fine.

Next: Classes and Objects, where you'll define your own classes, member functions and objects step by step.