Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 19 Beginner

Encapsulation and Abstraction in C++

Updated: May 17, 2026
5 min read

# CHAPTER 19

Encapsulation and Abstraction

1. Introduction

We touched on Encapsulation and Abstraction in Chapter 14 when discussing the pillars of OOP. Now, we will implement them deeply. Encapsulation is about *protecting* data. Abstraction is about *simplifying* the usage of that data. Together, they form the basis of secure, maintainable API design in C++.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Implement Encapsulation using private variables.
  • Write Getter and Setter methods.
  • Understand the concept of Data Hiding.
  • Implement Abstraction using interfaces.

3. Encapsulation: Data Hiding

If you allow main() to directly modify an object's variables, a user could set a bank account balance to a negative number, or a player's health to 10,000. Encapsulation prevents this by making the variables private.
cpp
1234
class Player {
  public:
    int health; // BAD! Anyone can change this.
};

The Solution:

cpp
1234
class Player {
  private:
    int health; // GOOD! Hidden from the outside.
};

4. Getters and Setters (Accessors and Mutators)

Since health is private, how does the rest of the program read or change it? We provide public functions called Getters (to read) and Setters (to write). This allows the class to validate the input before modifying the data.
cpp
123456789101112131415161718192021222324252627282930313233343536373839
#include <iostream>
using namespace std;

class Player {
  private:
    int health;

  public:
    // Constructor
    Player() { health = 100; }

    // GETTER: Returns the private data
    int getHealth() const {
        return health;
    }

    // SETTER: Modifies the private data WITH VALIDATION
    void setHealth(int newHealth) {
        if (newHealth < 0) {
            health = 0;
            cout << "Player is dead!" << endl;
        } else if (newHealth > 100) {
            health = 100; // Cap health at 100
        } else {
            health = newHealth;
        }
    }
};

int main() {
    Player p1;
    
    // p1.health = -50; // ERROR! Private!
    
    p1.setHealth(-50); // Setter catches the invalid input
    cout << "Current Health: " << p1.getHealth() << endl; // Uses getter
    
    return 0;
}

5. Abstraction in Practice

Abstraction hides the *implementation details* from the user. When you call sort() on an array, you don't need to know if it uses QuickSort or MergeSort; you just need it to sort.

In C++, true abstraction is achieved using Abstract Classes (classes with pure virtual functions) to act as Interfaces.

6. Creating an Interface

C++ does not have an interface keyword like Java or C#. Instead, we create a class where *all* functions are pure virtual.
cpp
12345678910111213141516171819202122
// This acts as an Interface
class IShape {
  public:
    virtual double calculateArea() = 0;
    virtual double calculatePerimeter() = 0;
};

// Circle must implement ALL functions in the Interface
class Circle : public IShape {
  private:
    double radius;
  public:
    Circle(double r) : radius(r) {}
    
    double calculateArea() override {
        return 3.14159 * radius * radius;
    }
    
    double calculatePerimeter() override {
        return 2 * 3.14159 * radius;
    }
};

7. Why use Interfaces?

Interfaces create a Contract. By having Circle inherit from IShape, we guarantee that Circle will definitely have an calculateArea function. If someone else is writing the UI code, they can safely write code that calls calculateArea without even knowing how Circle is implemented.

8. Memory-Level Explanation

Encapsulation (private/public) does NOT exist at runtime. It is purely a compile-time feature. The CPU does not know if a memory address is "private". The compiler enforces these rules to prevent programmers from writing bug-prone code.

9. Common Mistakes

  • Writing empty setters: A setter that just does health = newHealth; without any validation defeats the purpose of encapsulation. You might as well make the variable public.
  • Not using const on getters: A getter shouldn't modify the object. Writing int getHealth() const { ... } ensures the compiler throws an error if you accidentally try to change health inside the getter.

10. Exercises

  1. 1. Create a BankAccount class with a private balance and a private password. Create a withdraw(double amount, string pass) method that only allows withdrawal if the password matches and the balance is sufficient.
  1. 2. Create an IPlayable interface with play(), pause(), and stop() pure virtual functions. Implement it in a VideoPlayer class.

11. MCQ Quiz with Answers

Question 1

What is the primary purpose of Encapsulation?

Question 2

Which keyword is typically used to hide data in a class?

Question 3

What is a Getter?

Question 4

Why should a Setter contain validation logic (like if statements)?

Question 5

How do you create an Interface in C++?

Q6. Does Encapsulation exist in the compiled machine code running on the CPU? a) Yes b) No, it is a compile-time concept enforced by the compiler Answer: b) No, it is a compile-time concept enforced by the compiler
Question 7

Why add const to the end of a getter function signature?

Question 8

Abstraction focuses on:

Question 9

If Square inherits from IShape (an interface), what MUST Square do?

Q10. Can a class have both private variables and private functions? a) Yes b) No Answer: a) Yes (Private functions act as "helper" functions for the public methods).

12. Interview Questions

  • Q: In C++, how do you enforce an interface contract on a class?
  • Q: If you want a specific external function to access private variables without using getters, what C++ keyword can you use? (Answer: The friend keyword).
  • Q: Explain the difference between Abstraction and Encapsulation.

13. Summary

Encapsulation bundles data and methods, using private variables and public getters/setters to protect the integrity of an object's state. Abstraction simplifies complex systems by hiding the implementation details behind clean, predictable Interfaces made of pure virtual functions.

14. Next Chapter Recommendation

In Chapter 20: Templates in C++, we will learn how to write a function once and have it work with ints, floats, or any custom object without rewriting the code, unlocking Generic Programming.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·