OOP

const and non const Functions

In C++, const plays a crucial role in object-oriented programming (OOP) by defining the mutability (ability to change) of objects and their member functions. Here’s a breakdown of const functions and how they relate to OOP principles:

Const Functions:

Example:

class Account {
private:
    int balance;
public:
    Account(int initialBalance) : balance(initialBalance) {}

    // Const member function (guarantees no modification)
    int getBalance() const {
        return balance;
    }

    // Non-const member function (can modify)
    void deposit(int amount) {
        balance += amount;
    }
};

In this example, getBalance is a const function because it only retrieves the balance without changing it. deposit is a non-const function because it modifies the balance.

Non-Const Functions:

Relationship to OOP:

Choosing Between Const and Non-Const:

Additional Considerations:

By understanding const functions, you can write more robust, secure, and maintainable object-oriented code in C++.

Practice: