ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CSI-312
    Progress0 / 16 topics
    Topics
    1. Evolution of Object-Oriented (OO) Programming2. Object-Oriented (OO) Concepts and Principles3. Problem Solving in OO Paradigm4. OO Programme Design Process5. Classes6. Methods7. Objects and Encapsulation8. Constructors and Destructors9. Operator Overloading10. Function Overloading11. Virtual Functions12. Derived Classes13. Inheritance14. Polymorphism15. I/O and File Processing16. Exception Handling
    CSI-312›Objects and Encapsulation
    Object Oriented ProgrammingTopic 7 of 16

    Objects and Encapsulation

    8 minread
    1,348words
    Intermediatelevel

    Objects and Encapsulation in Object-Oriented Programming (OOP)

    Objects and Encapsulation are two fundamental concepts in Object-Oriented Programming (OOP) that work together to make code more modular, reusable, and maintainable.


    1. Objects in OOP

    In OOP, an object is an instance of a class. A class acts as a blueprint or template for creating objects. An object holds both data (attributes) and functions (methods) that operate on that data.

    Key Characteristics of Objects:

    • State: The attributes or properties of an object that represent its data (e.g., the color or model of a car).
    • Behavior: The methods or functions that define the actions an object can perform (e.g., a car can accelerate, brake, or honk).
    • Identity: Each object is distinct and can be uniquely identified, even if it has the same state as another object.

    Creating Objects in C++:

    To create an object in C++, you need to:

    1. Define a class that specifies the object's properties (attributes) and behaviors (methods).
    2. Use the new keyword (for dynamic allocation) or direct instantiation (on the stack) to create the object.

    Example:

    #include <iostream>
    using namespace std;
    
    class Car {
    public:
        string model;
        int year;
    
        // Method to display car details
        void displayInfo() {
            cout << "Car Model: " << model << ", Year: " << year << endl;
        }
    };
    
    int main() {
        // Creating an object of the class 'Car'
        Car myCar;
        myCar.model = "Toyota Corolla";
        myCar.year = 2020;
    
        myCar.displayInfo();  // Output: Car Model: Toyota Corolla, Year: 2020
        return 0;
    }
    

    Explanation:

    • Car myCar; creates an object myCar of class Car.
    • The displayInfo() method is called on myCar to print its state (model and year).

    2. Encapsulation in OOP

    Encapsulation is one of the core principles of OOP. It refers to the concept of bundling data (attributes) and the methods (functions) that operate on that data within a single unit or class.

    Encapsulation helps in:

    • Data Hiding: Restricting direct access to the internal state of an object and only allowing access via well-defined methods (getters and setters).
    • Control: By exposing only necessary operations and hiding the internal implementation, you can control how the data is accessed and modified.
    • Modularity: Encapsulation leads to better modularity because each object maintains its own state and operations, which can be changed independently of others.

    Components of Encapsulation:

    1. Private Members: Data members (attributes) that are hidden from outside the class, ensuring that they are not accessed or modified directly.
    2. Public Methods: Functions (methods) that are accessible from outside the class and serve as an interface to interact with the object.

    The two key mechanisms used to achieve encapsulation in C++ are:

    1. Access Modifiers (Private, Public, Protected)
    2. Getter and Setter Methods (Accessors and Mutators)

    Access Modifiers in C++:

    • private: Members are hidden and cannot be accessed directly from outside the class.
    • public: Members are accessible from anywhere in the program.
    • protected: Members are accessible within the class and its derived classes.

    Getter and Setter Methods (Accessors and Mutators):

    • Getter (Accessor): A method used to retrieve the value of a private attribute.
    • Setter (Mutator): A method used to set or modify the value of a private attribute.

    Example of Encapsulation:

    #include <iostream>
    using namespace std;
    
    class BankAccount {
    private:
        double balance;  // Private data member
    
    public:
        // Constructor to initialize balance
        BankAccount(double initialBalance) {
            if (initialBalance > 0) {
                balance = initialBalance;
            } else {
                balance = 0;
                cout << "Invalid initial balance. Setting balance to 0." << endl;
            }
        }
    
        // Getter method (accessor) to get balance
        double getBalance() {
            return balance;
        }
    
        // Setter method (mutator) to deposit money
        void deposit(double amount) {
            if (amount > 0) {
                balance += amount;
            } else {
                cout << "Deposit amount must be positive." << endl;
            }
        }
    
        // Method to withdraw money
        void withdraw(double amount) {
            if (amount > 0 && amount <= balance) {
                balance -= amount;
            } else {
                cout << "Invalid withdrawal amount." << endl;
            }
        }
    
        // Method to display balance
        void displayBalance() {
            cout << "Current Balance: $" << balance << endl;
        }
    };
    
    int main() {
        // Create an object of BankAccount with an initial balance
        BankAccount account(1000);
    
        // Display the current balance
        account.displayBalance();
    
        // Deposit money
        account.deposit(500);
        account.displayBalance();
    
        // Withdraw money
        account.withdraw(200);
        account.displayBalance();
    
        // Try invalid operations
        account.deposit(-50);  // Invalid deposit
        account.withdraw(2000);  // Invalid withdrawal
    
        return 0;
    }
    

    Explanation of Encapsulation in the Example:

    1. Private Data: The balance attribute is declared as private. This means it cannot be accessed directly from outside the class. You cannot modify or access the balance directly from the main() function.

    2. Public Methods:

      • The deposit() and withdraw() methods are mutators (setters) because they modify the balance.
      • The getBalance() method is a getter (accessor) because it allows you to retrieve the balance.
      • The displayBalance() method displays the current balance.
    3. Control:

      • The deposit() and withdraw() methods have checks to ensure valid operations (e.g., not depositing a negative amount or withdrawing more than the balance). This ensures the integrity of the balance attribute, which is hidden from direct modification.

    By using encapsulation, we achieve data hiding and controlled access to the internal state of the object, which makes the object more robust and less prone to errors or invalid states.


    Advantages of Encapsulation:

    1. Control over Data: Encapsulation allows the class to control how its data is accessed and modified. This prevents unauthorized or invalid access and modification of the object's state.

    2. Improved Security: By making data members private and providing public methods to interact with them, you prevent direct access to sensitive data, reducing the risk of unintended modifications or corruption.

    3. Flexibility and Maintenance: If the internal implementation needs to change, you can modify the methods without affecting the external code that interacts with the object. This makes your code more maintainable and flexible.

    4. Data Integrity: Encapsulation ensures that the object's state is always valid by controlling how data is modified (e.g., using validation logic in setters).


    Real-World Example of Encapsulation

    Consider a Car class where you can control the speed of the car through methods rather than directly modifying the speed attribute:

    class Car {
    private:
        int speed;  // Private data member for speed
    
    public:
        // Constructor to initialize the car's speed
        Car() {
            speed = 0;
        }
    
        // Setter method to accelerate the car
        void accelerate(int amount) {
            if (amount > 0) {
                speed += amount;
            } else {
                cout << "Acceleration amount must be positive." << endl;
            }
        }
    
        // Getter method to retrieve current speed
        int getSpeed() {
            return speed;
        }
    };
    
    int main() {
        Car myCar;
        myCar.accelerate(50);  // Accelerate the car by 50
        cout << "Current Speed: " << myCar.getSpeed() << " km/h" << endl;
    
        myCar.accelerate(-10);  // Invalid acceleration
        cout << "Current Speed: " << myCar.getSpeed() << " km/h" << endl;
    
        return 0;
    }
    

    In this example:

    • The speed attribute is encapsulated and cannot be accessed directly.
    • The accelerate() method allows controlled modification of the speed.
    • The getSpeed() method provides read access to the speed.

    This kind of encapsulation ensures that the internal state of an object (like speed) is always consistent and that no external code can modify it directly without going through the appropriate checks.


    Conclusion

    • Objects are instances of classes, and they encapsulate both data and behavior.
    • Encapsulation is the practice of hiding an object's internal state and requiring all interaction to be done through methods (getters and setters).
    • Encapsulation provides data security, control, flexibility, and maintainability by restricting direct access to an object's internal data, ensuring that it is accessed and modified in a controlled and predictable way.
    Previous topic 6
    Methods
    Next topic 8
    Constructors and Destructors

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,348
      Code examples0
      DifficultyIntermediate