Understanding Public and Private Access Specifiers in C++

Understanding Public and Private Access Specifiers in C++

Table of Contents

  1. Introduction
  2. Public Access Specifier
  3. Private Access Specifier
  4. Accessing Member Variables Outside of the Class
  5. Accessing Member Functions Outside of the Class
  6. Getter and Setter Functions
  7. Encapsulation and Information Hiding
  8. Validating Input with Setter Functions
  9. Private Member Functions
  10. Print Bonus Function
  11. Conclusion

🔍 Introduction

In this article, we will explore the difference between the public and private access specifiers in C++. Access specifiers determine the accessibility of class members, such as variables and functions, from outside the class. We will look at examples to understand how these access specifiers work and how they affect the visibility and usability of class members.

🔐 Public Access Specifier

The public access specifier allows the class members to be accessed and used both within and outside of the class. When a member variable or function is declared as public, it can be accessed directly outside the class by using the object of that class. For example:

class Employee {
public:
    std::string name; // Public member variable
};

In the above example, the name member variable of the Employee class is declared as public. This means it can be accessed outside the class using an object of the Employee class. For instance:

Employee employee1;
employee1.name = "Kevin";
std::cout << employee1.name << std::endl; // Output: Kevin

🔒 Private Access Specifier

On the other hand, the private access specifier restricts the accessibility of class members to within the class only. When a member variable or function is declared as private, it cannot be accessed directly outside the class. For example:

class Employee {
private:
    double salary; // Private member variable
};

In the above example, the salary member variable of the Employee class is declared as private. This means it cannot be accessed outside the class. If we try to access it, we will encounter a compiler error. For instance:

Employee employee1;
employee1.salary = 50000; // Compiler error: 'salary' is a private member of 'Employee'

💻 Accessing Member Variables Outside of the Class

As mentioned earlier, public member variables can be accessed outside the class. This allows us to modify or retrieve the value of the member variable directly using the object of the class. For example:

Employee employee1;
employee1.name = "Kevin";
std::cout << employee1.name << std::endl; // Output: Kevin

In this example, the name member variable is accessible outside the class, and we can assign a value to it or retrieve its value directly.

⚙️ Accessing Member Functions Outside of the Class

In addition to member variables, member functions can also have access specifiers. The accessibility of member functions works similarly to member variables. If a member function is declared as public, it can be called outside the class using an object of that class. For example:

class Employee {
public:
    double getSalary() { // Public member function
        return salary;
    }
};

In the above example, the getSalary() member function of the Employee class is declared as public. This means it can be called outside the class using an object of the Employee class. For instance:

Employee employee1;
double salary = employee1.getSalary();
std::cout << "Salary: " << salary << std::endl;

Here, we are accessing the getSalary() member function outside the class to retrieve the value of the salary member variable.

🔄 Getter and Setter Functions

Getter and setter functions are commonly used with private member variables to provide controlled access and modification of the variable's value. A getter function retrieves the value of a private member variable, while a setter function allows the modification of the variable's value. For example:

class Employee {
private:
    double salary;
public:
    double getSalary() { // Getter function
        return salary;
    }
    void setSalary(double potentialSalary) { // Setter function
        if (potentialSalary < 0) {
            salary = 0;
        } else {
            salary = potentialSalary;
        }
    }
};

In the above example, the getSalary() function is a getter function that retrieves the value of the private salary member variable. The setSalary() function, on the other hand, is a setter function that sets the value of the salary member variable after validating the input. We can use these functions to access and modify the private member variable. For example:

Employee employee1;
employee1.setSalary(50000);
double salary = employee1.getSalary();
std::cout << "Salary: " << salary << std::endl;

In this example, we set the salary of employee1 using the setSalary() function and then retrieve the salary using the getSalary() function.

🏷️ Encapsulation and Information Hiding

Encapsulation is an object-oriented programming concept that combines data and functions into a single unit called a class. It allows for the bundling of data and functions and provides control over their accessibility. The use of access specifiers, such as public and private, is a way to implement encapsulation.

Private member variables and functions are an example of information hiding, where the inner workings and implementation details of a class are kept private and hidden from the outside world. This provides abstraction and allows for better control and management of the class's behavior.

By using private member variables and functions, we can ensure that the data and operations within a class are accessed and modified only through the defined public interfaces, such as getter and setter functions. This helps maintain the integrity and consistency of the class's data.

✅ Validating Input with Setter Functions

One advantage of using getter and setter functions is the ability to validate and control the input before modifying the private member variable. This ensures that the data remains valid and consistent.

For example, in the setSalary() function, we perform a validation check to ensure that the potential salary is not less than zero. If it is, we set the salary to zero. This prevents the possibility of having negative salaries for employees.

void setSalary(double potentialSalary) {
    if (potentialSalary < 0) {
        salary = 0;
    } else {
        salary = potentialSalary;
    }
}

By incorporating validation checks within the setter function, we can enforce business rules and maintain the integrity of the data stored in the private member variable.

🕵️ Private Member Functions

In addition to private member variables, we can also have private member functions. Private member functions are functions that can only be accessed and called from within the class. They are typically used for internal operations and implementation details that are not meant to be exposed to the outside world.

For example, let's create a private member function called calculateBonus() that calculates the yearly bonus based on the employee's salary:

class Employee {
private:
    double salary;

    double calculateBonus() { // Private member function
        return salary * 0.10; // Bonus is 10% of the salary
    }
};

In the above example, the calculateBonus() function is declared as private. This means it cannot be accessed outside the class. If we try to access it, we will encounter a compiler error. This restriction ensures that the bonus calculation remains internal to the class and is not accessible or modified from the outside.

📄 Print Bonus Function

To provide a way to access and display the bonus to the outside world, we can create a public member function called printBonus(). This function will call the private calculateBonus() function internally and display the bonus along with the employee's name.

class Employee {
public:
    void printBonus() { // Public member function
        double bonus = calculateBonus();
        std::cout << "Bonus: " << bonus << std::endl;
    }

private:
    double salary;

    double calculateBonus() { // Private member function
        return salary * 0.10; // Bonus is 10% of the salary
    }
};

In this example, the printBonus() function is a public member function that can be called outside the class. Inside the function, we call the private calculateBonus() function to calculate the bonus and display it along with the employee's name. For instance:

Employee employee1;
employee1.printBonus(); // Output: Bonus: 5000 (assuming a salary of 50000)

📝 Conclusion

In conclusion, the public and private access specifiers in C++ provide control over the accessibility of class members. Public members can be accessed and used both within and outside the class, while private members can only be accessed internally within the class.

Access specifiers allow for encapsulation and information hiding, where the internal details and implementation of a class are kept private and hidden. By using getter and setter functions, we can provide controlled access to private member variables and enforce validation checks. Private member functions can be used for internal operations and implementation details that are not meant to be exposed.

Understanding the differences between public and private access specifiers is fundamental in creating robust and secure class designs.

🌐 Resources


Highlights

  • Public access specifier allows for the accessibility of class members both within and outside the class.
  • Private access specifier restricts the accessibility of class members to only within the class.
  • Getter and setter functions can be used with private member variables to control access and modification.
  • Encapsulation and information hiding help maintain the integrity and consistency of class data.
  • Private member functions are used for internal operations and implementation details.

FAQs

Q: What is the purpose of access specifiers? A: Access specifiers control the accessibility of class members, such as variables and functions, from outside the class. They help enforce encapsulation and provide controlled access to class members.

Q: Can we access private member variables outside the class? A: No, private member variables cannot be accessed directly outside the class. They can only be accessed and modified through getter and setter functions or other public member functions.

Q: Why do we use getter and setter functions for private member variables? A: Getter and setter functions allow for controlled access and modification of private member variables. They provide a way to validate input, enforce business rules, and maintain the consistency of the data stored in the member variables.

Q: Can we have private member functions in C++? A: Yes, private member functions are functions that can only be accessed and called from within the class. They are typically used for internal operations and implementation details.

Q: What is information hiding in object-oriented programming? A: Information hiding is a principle in object-oriented programming where the inner workings and implementation details of a class are kept private and hidden. It allows for better abstraction and control over how the class is used and accessed.

Q: Where can I learn more about building an impressive portfolio? A: Check out ChecoPortfolioCourses at http://checoportfoliocourses.com for resources and guidance on building a portfolio that will impress employers.

I am an ordinary seo worker. My job is seo writing. After contacting Proseoai, I became a professional seo user. I learned a lot about seo on Proseoai. And mastered the content of seo link building. Now, I am very confident in handling my seo work. Thanks to Proseoai, I would recommend it to everyone I know. — Jean

Browse More Content