Contenido del Curso
C++ OOP
C++ OOP
Access 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
: accessible only within the same class and are hidden from outside the class. This is the default access level for class members;protected
: accessible within the class and its derived classes. They are more accessible thanprivate
members but still provide a level of data protection;public
: accessible from any part of the program. Whilepublic
members are not encapsulated, they are essential for defining the interface that the class exposes to external entities.
The access modifier keeps applying until another one is specified or met.
main
#include <iostream> class Person { public: std::string name; }; int main() { Person person; person.name = "Bob"; std::cout << person.name; }
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
orprotected
;Provide
public
methods to access and modify theprivate
data;Ensure that these methods do only what they are intended to do, without revealing the internal logic.
A well-encapsulated class
should expose only what is necessary for the users and hide its internal state and implementation details.
¡Gracias por tus comentarios!