Lesson Overview

Hello! In this lesson, we're revisiting Encapsulation, Private Attributes, and Private Methods in Object-Oriented Programming (OOP). Imagine encapsulation as an invisible fence safeguarding a garden from outside interference, keeping data and methods safe within. Within this garden, certain plants (Private Attributes and Private Methods) are only for the gardener's eyes. These are crucial for making your classes more robust and secure!

Into the Encapsulation

Encapsulation in OOP wraps up data and methods into a class. This organizational approach tidies the code and reinforces security. If you were to code a multiplayer game, for example, you could create a Player class, encapsulating data (health, armor, stamina) and methods (receiveDamage, shieldHit, restoreHealth).

#include <iostream>
using namespace std;

class Player {
public:
    // Constructor
    Player(int health, int armor, int stamina) :
        health(health), armor(armor), stamina(stamina) {}

    // Public methods
    void receiveDamage(int damage) {
        health -= damage; // Reduce health
    }

    void shieldHit(int armorDecrease) {
        armor -= armorDecrease; // Decrease armor
    }

    void restoreHealth(int healthIncrease) {
        health += healthIncrease; // Restore health
    }

private:
    // Private attributes
    int health;
    int armor;
    int stamina;
};

int main() {
    Player player(100, 50, 77);
    player.receiveDamage(10);
    player.shieldHit(5);
    player.restoreHealth(15);
    return 0;
}

Now, player is an instance of the Player class on which you can call methods.

Remark the Privacy

In C++, the private access specifier designates attributes or methods as private. Private members are only accessible within the same class.

#include <iostream>
using namespace std;

class PrivateExample {
public:
    PrivateExample() {
        publicAttribute = "Public";
        privateAttribute = "Private";
    }

    // Method to print attributes (for demonstration purposes)
    void printAttributes() const {
        cout << "Public Attribute: " << publicAttribute << endl;
        // This line is fine inside the class method
        cout << "Private Attribute: " << privateAttribute << endl;
    }

    string publicAttribute; // Public attribute

private:
    string privateAttribute; // Private attribute
};

int main() {
    PrivateExample example;
    example.printAttributes();
    // This line is fine because publicAttribute is public
    cout << example.publicAttribute << endl;
    // Uncommenting the following line would cause an error because privateAttribute is private
    // cout << example.privateAttribute << endl;
    return 0;
}

Private attributes and methods are inaccessible directly from an instance in non-member functions. This arrangement helps maintain integrity. Moreover, in C++, if no access specifier is provided, methods and attributes are private by default; this default behavior helps ensure that class internals are not accidentally exposed.

Private Attributes

Private Attributes, which can only be altered via class methods, limit outside interference. For instance, a BankAccount class might feature a balance private attribute that one could change only through deposits or withdrawals.

#include <iostream>
using namespace std;

class BankAccount {
public:
    // Constructor
    BankAccount(int accountNumber, double balance) :
        accountNumber(accountNumber), balance(balance) {}

    // Public method to deposit money
    void deposit(double amount) {
        balance += amount; // Deposit money
    }

    // Method to print balance (for demonstration purposes)
    void printBalance() const {
        cout << "Balance: " << balance << endl;
    }

private:
    // Private attributes
    int accountNumber;
    double balance;
};

int main() {
    BankAccount bankAccount(1234, 100.0);
    bankAccount.printBalance();
    // Uncommenting the following line would cause an error because balance is private
    // cout << bankAccount.balance << endl;
    return 0;
}

Here, balance is private, thus ensuring the integrity of the account balance.

Private Methods

Like private attributes, private methods are accessible only within their class. Here's an example:

#include <iostream>
using namespace std;

class BankAccount {
public:
    // Constructor
    BankAccount(int accountNumber, double balance) :
        accountNumber(accountNumber), balance(balance) {}

    // Public method calling the private method
    void addYearlyInterest() {
        addInterest(0.02); // Adds 2% interest
    }

    // Method to print balance (for demonstration purposes)
    void printBalance() const {
        cout << "Balance: " << balance << endl;
    }

private:
    // Private method
    void addInterest(double interestRate) {
        balance += balance * interestRate; // Calculation of interest
    }

    // Private attributes
    int accountNumber;
    double balance;
};

int main() {
    BankAccount bankAccount(1234, 100.0);
    bankAccount.addYearlyInterest();
    bankAccount.printBalance();
    // Uncommenting the following line would cause an error because addInterest is private
    // bankAccount.addInterest(0.1);
    return 0;
}

Here, addYearlyInterest is a public method that calls the private method addInterest.

Lesson Summary and Practice

Great job refreshing your understanding of encapsulation, private attributes, and private methods concepts in C++! Correctly understanding and applying these foundational principles of OOP make your code concise, robust, and secure.

Coming up next is hands-on practice. Keep up the good work – exciting exercises are just around the corner!

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