Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Access Modifiers Keywords | Encapsulation Overview
C++ OOP
course content

Contenido del Curso

C++ OOP

C++ OOP

1. Fundamentals of OOP
2. Constructors and Destructors
3. Encapsulation Overview
4. Inheritance Overview
5. Polymorphism Overview

bookAccess Modifiers Keywords

Encapsulation in is primarily achieved using access modifiers. These modifiers control the level of access other parts of the program have to the members (both data and functions) of a class. The three primary access modifiers are:

  • private: members are accessible only within the same class and are hidden from outside the class. This is the default access level for class members;

  • protected: members are accessible within the class and its derived classes. They are more accessible than private members but still provide a level of data protection;

  • public: members are accessible from any part of the program. While public members are not encapsulated, they are essential for defining the interface that the class exposes to external entities.

Note

The access modifier keeps applying until another one is specified or met.

cpp

main

copy
12345678910111213
#include <iostream> class Person { public: std::string name; }; int main() { Person person; person.name = "Bob"; std::cout << person.name; }

Note

Try to delete or change public keyword and see what will happen.

Similar to how a driver can operate a car without understanding its internal mechanics, users and programmers don't need to be concerned about private attributes and methods within a class. Follow these rules:

  • keep data members private or protected;

  • provide public methods to access and modify the private data;

  • ensure that these methods do only what they are intended to do, without revealing the internal logic.

A well-encapsulated class in should expose only what is necessary for the users and hide its internal state and implementation details.

What will happen if you try to access a private member of a class directly from outside the class?

What will happen if you try to access a private member of a class directly from outside the class?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 2
We're sorry to hear that something went wrong. What happened?
some-alt