C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

Class Members Access Permissions and Class Encapsulation in C++

In C++, access permissions (also called access specifiers) determine the visibility and accessibility of class members (variables and functions). Encapsulation is a fundamental concept in object-oriented programming that binds together data and functions that manipulate the data while hiding the implementation details from the user.

There are three access permissions in C++:

  1. public: Members declared as public are accessible from any part of the program.
  2. private: Members declared as private are accessible only within the class itself.
  3. protected: Members declared as protected are accessible within the class and its derived classes (subclass).

Encapsulation

Encapsulation is achieved in C++ by using access permissions to restrict direct access to class members. Encapsulation helps to:

  1. Protect the internal state of an object from being directly manipulated by external code.
  2. Abstract the implementation details from the user, allowing the internal implementation to change without affecting the external interface.
  3. Improve maintainability and modularity of the code.

Class Definition with Access Permissions

Here's an example of a class definition with public, private, and protected access permissions:

class MyClass {
public: // Public members
    int publicVar;
    void publicFunction();

private: // Private members
    int privateVar;
    void privateFunction();

protected: // Protected members
    int protectedVar;
    void protectedFunction();
};

Using Encapsulation

In the example below, we will create a simple BankAccount class that uses encapsulation to protect the account balance and provide public methods for depositing and withdrawing funds.

#include <iostream>

class BankAccount {
private:
    double balance;

public:
    BankAccount() : balance(0) {}

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            std::cout << "Deposited: " << amount << std::endl;
        } else {
            std::cout << "Invalid deposit amount" << std::endl;
        }
    }

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            std::cout << "Withdrew: " << amount << std::endl;
        } else {
            std::cout << "Invalid withdrawal amount" << std::endl;
        }
    }

    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account;
    account.deposit(100);
    account.withdraw(50);
    std::cout << "Account balance: " << account.getBalance() << std::endl;

    // Error: 'double BankAccount::balance' is private within this context
    // std::cout << "Account balance: " << account.balance << std::endl;

    return 0;
}

In this example, the account balance is protected by making it private. The class provides public methods to deposit and withdraw funds, enforcing any necessary constraints (e.g., only allowing positive amounts). The user can access the balance using the getBalance() method, but cannot directly modify it.

In conclusion, class members access permissions and encapsulation are essential concepts in C++ for designing robust, maintainable, and modular code. By using access permissions to control the visibility and accessibility of class members, encapsulation allows you to hide the internal state and implementation details of a class, protecting the data and providing a clean external interface.

  1. Encapsulation in C++ with examples:

    • Description: Encapsulation is one of the fundamental principles of object-oriented programming, where data and methods that operate on the data are bundled together within a class.
    • Example Code:
      #include <iostream>
      
      class EncapsulationExample {
      private:
          int privateData;
      
      public:
          void setPrivateData(int value) {
              privateData = value;
          }
      
          int getPrivateData() const {
              return privateData;
          }
      };
      
      int main() {
          EncapsulationExample obj;
          obj.setPrivateData(42);
          std::cout << "Private Data: " << obj.getPrivateData() << std::endl;
      
          return 0;
      }
      
  2. Private, public, and protected members in C++ classes:

    • Description: C++ classes allow members to have different access specifiers - private, public, and protected, controlling their visibility and accessibility.
    • Example Code:
      class AccessExample {
      private:
          // private members
      
      public:
          // public members
      
      protected:
          // protected members
      };
      
  3. C++ class member access control:

    • Description: Describes how access specifiers control the visibility of class members.
    • Example Code:
      class AccessControlExample {
      private:
          int privateMember;
      
      public:
          int publicMember;
      
      protected:
          int protectedMember;
      };
      
  4. Friend functions and classes in C++:

    • Description: Explains the concept of friend functions and classes, which can access private and protected members of a class.
    • Example Code:
      class MyClass {
          int privateMember;
      
      public:
          friend void friendFunction(MyClass obj);
      };
      
      void friendFunction(MyClass obj) {
          std::cout << "Friend Function accessing privateMember: " << obj.privateMember << std::endl;
      }
      
  5. C++ access specifiers and inheritance:

    • Description: Explains how access specifiers work in the context of inheritance, influencing the visibility of inherited members.
    • Example Code:
      class Base {
      protected:
          int protectedMember;
      };
      
      class Derived : public Base {
      public:
          void accessProtected() {
              std::cout << "Accessing protectedMember from Derived: " << protectedMember << std::endl;
          }
      };