C++ Access Specifiers and Encapsulation

Encapsulation means keeping the data private and giving controlled access with public methods, so the object can not get a wrong state.

SpecifierWho can use the member
publicEveryone
protectedThe class and its derived classes
privateOnly the class itself (and friends)
#include <iostream>
#include <stdexcept>

class Account {
public:
    void deposit(double amount) {
        if (amount <= 0) throw std::invalid_argument("Deposit must be positive");
        balance += amount;
    }
    void withdraw(double amount) {
        if (amount > balance) throw std::runtime_error("Not enough balance");
        balance -= amount;
    }
    double get_balance() const { return balance; }       // getter
private:
    double balance = 0;
};

int main() {
    Account a;
    a.deposit(1000);
    a.withdraw(250);
    std::cout << a.get_balance() << '\n';
    try {
        a.withdraw(5000);
    } catch (const std::exception& e) {
        std::cout << "Error: " << e.what() << '\n';
    }
}
Output

750
Error: Not enough balance

A direct access to a private member is an error:

class Account {
    double balance = 0;
};

int main() {
    Account a;
    a.balance = -5000;
}
Output

Private.cpp: In function 'int main()':
Private.cpp:7:7: error: 'double Account::balance' is private within this context
7 | a.balance = -5000;
| ^~~~~~~
Private.cpp:2:12: note: declared private here
2 | double balance = 0;
| ^~~~~~~

static members

#include <iostream>

class Student {
public:
    Student() { count++; }
    static int count;                    // one copy for the whole class
    static int total() { return count; }
};

int Student::count = 0;                  // definition outside the class

int main() {
    Student a, b, c;
    std::cout << Student::count << ' ' << Student::total() << '\n';
}
Output

3 3

friend

A friend function or class can use the private members. Use it rarely, for example for operator<<.

#include <iostream>

class Box {
public:
    explicit Box(int s) : secret(s) {}
    friend void peek(const Box& b);
private:
    int secret;
};

void peek(const Box& b) { std::cout << "Secret: " << b.secret << '\n'; }

int main() {
    peek(Box(7));
}
Output

Secret: 7

Note: Make all data members private, and add getters only when needed. A const method promises not to change the object. Next: C++ Inheritance.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.