Encapsulation in C++

Lesson Introduction

Hello! Today, we're learning about encapsulation in C++. Encapsulation bundles data and the methods that operate on that data into a single unit called a class. It's used to protect our data from access or modifications from outside the class.

Our goal is to understand encapsulation, how to implement it using private and public members in a class, and why it helps keep our code safe and organized. We'll use an example: solving a quadratic equation and learn to protect critical values.

Understanding Encapsulation

Encapsulation is a core principle of object-oriented programming. It combines data and methods into one unit, called a class. This helps us hide the internal state of the object and only expose what's necessary.

Think of encapsulation like a pill capsule. Inside the capsule, there are different ingredients (data), but when you swallow it, you don't interact with these ingredients directly. Similarly, encapsulation helps control how data is accessed and modified.

In C++, we use private and public access specifiers to implement encapsulation. Private members are variables and methods that cannot be accessed directly from outside the class. We use them to hide the internal state of the object.

The Private Access Specifier

#include <iostream>

class Example {
private:
    int hiddenData;
};

int main() {
    Example obj;
    obj.hiddenData = 10;  // Will cause an error, because hiddenData is private!
    return 0;
}

In this example, hiddenData is a private member of the Example class. It is not accessible directly outside the class, and trying to access obj.hiddenData will result in a compilation error.

Step-by-Step Code Walkthrough: Part 1

Let's go through the full code example to see how encapsulation is implemented to solve a quadratic equation.

#include <iostream>
#include <cmath>
#include <stdexcept>  // For invalid_argument

class QuadraticEquation {
private:
    int a; 
    int b; 
    int c;

public:
    // Constructor
    QuadraticEquation(int a, int b, int c) {
        if (a != 0) {
            this->a = a;
        } else {
            throw std::invalid_argument("Coefficient a cannot be zero.");
        }
        this->b = b;
        this->c = c;
    }

Notice that we have declared a, b, and c as private members. This is the essence of encapsulation; we're hiding these members from direct access outside the class. Importantly, to protect our class from setting a to zero (which would result in a division by zero during calculation), we make a private. By doing this, we prevent unintended modifications from external code. Though b and c can take any values and don't require special protection, it is common to make all the class attributes private to ensure we can control access to them in the future.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal