Introduction

Welcome! Today's subject is Encapsulation, a cornerstone of Object-Oriented Programming (OOP) in C++. Encapsulation is the process of bundling data and the operations that modify them into one unit — commonly an object — thereby protecting the data from unwanted alterations. This level of data protection ensures the creation of robust and maintainable software.

Prepare yourself for an exciting journey as we delve into how encapsulation functions in C++ and explore the critical role it plays in safeguarding data privacy.

Unraveling Encapsulation

Starting with the basics, encapsulation involves wrapping data and the methods that modify this data into a single compartment known as a class. It protects the internal state of an object from undesired external interference.

To illustrate, consider a C++ class representing a bank account. Without encapsulation, the account balance could be directly altered. With encapsulation, however, the balance can only change through specified methods such as deposit or withdraw.

class BankAccount {
public:
    void deposit(double amount);
    void withdraw(double amount);
    double checkBalance() const;

private:
    int accountNumber;
    double balance;
};
Encapsulation: Guardian of Data Privacy

Encapsulation restricts direct access to an object's data and prevents unwanted data alteration. This principle is comparable to window blinds, allowing you to look out while preventing others from peeping in.

In C++, encapsulation is achieved through access specifiers like private and public. By default, class members are private, restricting direct access. Data intended to be hidden from outside manipulation is placed under the private access specifier, while public members are accessible.

Consider a class Person with a private attribute name.

class Person {
public:
    Person(std::string name) : name(name) {}
    std::string getName() const;

private:
    std::string name; // Private attribute
};

std::string Person::getName() const {
    return name;
}

In this example, name is private, and getName() enables us to access it safely.

Getter and Setter Methods in Encapsulation

While encapsulating, C++ uses getter and setter methods to access or modify private attributes. A getter method retrieves an attribute's value, while a setter alters it. Let's illustrate this:

class Dog {
public:
    Dog(std::string name) : name(name) {}
    void setName(std::string newName);
    std::string getName() const;

private:
    std::string name; // Private attribute
};

void Dog::setName(std::string newName) {
    name = newName;
}

std::string Dog::getName() const {
    return name;
}

Here, setName() and getName() serve as the setter and getter methods, respectively, for the private attribute name.

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