Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Data Hiding in C++(Accessors & Mutators)

Data Hiding

Data hiding is a fundamental concept in object-oriented programming (OOP) that refers to the practice of restricting access to certain details of an object’s implementation. In C++, data hiding is primarily achieved through the use of access modifiers like private and protected, which prevent external code from directly accessing or modifying the internal data of a class.

Purpose of Data Hiding:

  • Reducing Complexity: By hiding unnecessary details from the outside world, data hiding helps reduce complexity. The user of the class doesn’t need to know how the class is implemented; they only need to know how to use it.
  • Control: By hiding data, a class can control how its attributes are accessed or modified. This allows the class to enforce rules, validations, and constraints on the data.
  • Maintainability: It makes the code easier to maintain and update because the internal representation of data can be changed without affecting the external code that uses the class.

How Data Hiding is Achieved in C++:

  1. Private Access Modifier:
    • Members declared as private are accessible only within the same class. They cannot be accessed directly from outside the class.
    • This is the most common way to hide data in C++.
  2. Protected Access Modifier:
    • Members declared as protected are accessible within the same class and by derived classes (inherited classes). However, they are still not accessible by external code.

Hidden Data is Access by :

  • Accessor: An accessor is a method or function used to read or “access” the value of a private data member in a class. It’s commonly called a getter function.
  • Mutator :A mutator is a method or function used to modify or “mutate” the value of a private data member in a class. It’s commonly called a setter function.

Example: Student Class with Data Hiding

In this example, the grade of a student is kept private, meaning it cannot be accessed or modified directly from outside the class. Instead, public methods are provided to safely interact with the grade.

Code
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
    string name;  // Private member to store the student's name
    int age;           // Private member to store the student's age

public:
    // Mutator (Setter) for the name
    void setName(const string& studentName) {
        name = studentName;
    }

    // Accessor (Getter) for the name
    string getName() const {
        return name;
    }

    // Mutator (Setter) for the age
    void setAge(int studentAge) {
        if (studentAge > 0) {  // Simple validation to ensure a positive age
            age = studentAge;
        } else {
            cout << "Invalid age! Age must be positive." << endl;
        }
    }

    // Accessor (Getter) for the age
    int getAge() const {
        return age;
    }
};

int main() {
    Student student;  // Create a Student object

    // Set the student's name and age using mutator methods
    student.setName("John Doe");
    student.setAge(20);

    // Access and print the student's name and age using accessor methods
    cout << "Student Name: " << student.getName() << endl;
    cout << "Student Age: " << student.getAge() << endl;

    return 0;
}

Output:

Student Name: John Doe
Student Age: 20
Explanation:

Step 1: Class Definition

  • Private Members: name and age are private, which means they cannot be accessed directly from outside the class. This encapsulates the data, providing control over how it’s accessed and modified.
class Student {
private:
    string name;  // Private member to store the student's name
    int age;      // Private member to store the student's age

Step 2: Mutator (Setter) Methods:

  • setName: This method allows setting the name of the Student object. It takes a const string& as an argument, which is efficient for large strings.
  • setAge: This method allows setting the age of the Student object. It includes validation to ensure that the age is positive. If the age is invalid, it prints an error message.
public:
    // Mutator (Setter) for the name
    void setName(const string& studentName) {
        name = studentName;
    }
    
    // Mutator (Setter) for the age
    void setAge(int studentAge) {
        if (studentAge > 0) {  // Simple validation to ensure a positive age
            age = studentAge;
        } else {
            cout << "Invalid age! Age must be positive." << endl;
        }
    }

Step3: Accessor (Getter) Methods

  • getName: This method returns the name of the Student object. It is marked const, indicating that it does not modify the object.
  • getAge: This method returns the age of the Student object. It is also marked const.
    // Accessor (Getter) for the name
    string getName() const {
        return name;
    }

    // Accessor (Getter) for the age
    int getAge() const {
        return age;
    }

Step 4: Main Function:

  • Create Object: Student student; creates a Student object named student.
  • Set Data:
  • student.setName("John Doe"); sets the student’s name to “John Doe”.
    • student.setAge(20); sets the student’s age to 20.
  • Get and Print Data:
  • cout << "Student Name: " << student.getName() << endl; prints the student’s name.
    • cout << "Student Age: " << student.getAge() << endl; prints the student’s age.
int main() {
    Student student;  // Create a Student object

    // Set the student's name and age using mutator methods
    student.setName("John Doe");
    student.setAge(20);

    // Access and print the student's name and age using accessor methods
    cout << "Student Name: " << student.getName() << endl;
    cout << "Student Age: " << student.getAge() << endl;

    return 0;
}

    Leave a Reply

    Your email address will not be published.

    Need Help?