C++

Classes, Public and Private access modifiers in C++

826
0
Classes, Public and Private access modifiers in C++

Classes in C++

A class in C++ is a blueprint for creating objects that have data members (attributes) and member functions (methods) to manipulate those data members. It is a user-defined data type that can have access modifiers to control the visibility of its members.

Access Modifiers

C++ provides three access modifiers that can be used to specify the visibility of the members of a class:

  • public: Members declared as public are accessible from anywhere outside the class. They can be accessed by objects of the class and by non-member functions.
  • private: Members declared as private are accessible only within the class. They cannot be accessed by objects of the class or by non-member functions.
  • protected: Members declared as protected are accessible within the class and its subclasses (derived classes). They cannot be accessed by objects of the class or by non-member functions.

The access modifiers can be used to enforce encapsulation, which is the principle of hiding the implementation details of a class from the outside world. By making the data members private and providing public member functions to access and modify them, we can control the way in which the data is accessed and prevent unwanted modifications.

Example

Here is an example of a class with public and private members:

class Person {
public:
    // Public members
    std::string name;
    int age;
    void greet() {
        std::cout << "Hello, my name is " << name << " and I am " << age << " years old.\n";
    }
private:
    // Private members
    std::string password;
};
C++

In this example, the name and age data members are declared as public, so they can be accessed from outside the class. The greet() member function is also declared as public, so it can be called by objects of the class and by non-member functions.

On the other hand, the password data member is declared as private, so it can only be accessed from within the class. This means that other functions and objects outside the class cannot access it directly.

Using Access Modifiers

Here is an example of how to use the access modifiers:

Person person;
person.name = "John";
person.age = 25;
person.greet();

person.password = "secret"; // Error: 'password' is private within this context
C++

In this example, we create an object of the Person class and set its name and age data members. We then call the greet() member function to print out a greeting.

However, if we try to access the password data member directly, we get a compile-time error because it is declared as private. This shows how access modifiers can be used to enforce encapsulation and prevent unwanted modifications to the data members.

xalgord
WRITTEN BY

xalgord

Constantly learning & adapting to new technologies. Passionate about solving complex problems with code. #programming #softwareengineering

Leave a Reply