You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
8 Hrs
30 Min
18 Seg

Encapsulación

10/16
Resources

What is encapsulation in object-oriented programming?

Encapsulation is a fundamental pillar in object-oriented programming (OOP) that focuses on restricting access to certain components of an object and protecting its internal structure. This is achieved by hiding data and allowing access only through established methods. This technique seeks to ensure that variables and methods are well protected from improper access from outside the object. In addition, it improves modularity and facilitates code maintenance.

Why is it important?

  1. Data security: By encapsulating data, data is prevented from being improperly modified by the outside of the object.
  2. Control: Allows greater control over how the object's state is accessed and modified.
  3. Maintenance: Facilitates software maintenance and evolution since internal details can be changed without affecting the exterior.
  4. Modularity: Improves code organization and helps to divide it into more manageable parts.

How to implement encapsulation in C++?

To implement encapsulation in C++, the private access modifier is commonly used. This restricts direct access to the attributes of a class, allowing access to them only through methods of the class.

Code example

Let's see how encapsulation is applied in a Person class:

class Person {private: std::string name; int age;
public: Person(std::string n, int e) : name(n), age(e) {}
 void greet() { std::cout << "Hello, my name is " << name << " and I am " << age << " years old." << std::endl; }
 void changeName(std::string newName) { name = newName; }
 void changeAge(int newAge) { age = newAge; } };

In this example, name and age are private attributes. They are accessed only through public methods such as greet, changeName, and changeAge.

Keyword protected

In addition to private, there is the protected modifier, which is useful in cases of inheritance. Protected attributes are accessible in derived classes, which provides additional flexibility.

What is inline assignment?

Inline assignment is a technique that allows you to assign variables to attributes in the constructor in a more concise manner. It is particularly useful for initializing attributes directly when declaring them, eliminating intermediate steps in the process.

Implementation in C++

In a constructor, the inline assignment is performed like this:

Person(std::string n, int e) : name(n), age(e) {}

This simplifies the code and is especially beneficial when handling multiple attributes. You can continue to separate each attribute with commas if you need to initialize more attributes.

Resources for deeper understanding of encapsulation

Proper understanding and application of encapsulation comes with practice and continued study. If you want to learn more about encapsulation and other Object Oriented Programming concepts, I recommend taking specialized courses that will broaden your knowledge and prepare you to develop more secure and efficient software.

Keep exploring and practicing to master this essential technique in software development - don't stop and keep learning!

Contributions 8

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

Para modificar o acceder al estado de los miembros (variables) privados, lo podemos hacer por medio de metodos (funciones) publicos, como serian los Getters y Setters de Java.

...
void setNombre(string nombre) {
	this->nombre = nombre;
}

string getNombre(void) {
	return nombre;
}
...
Persona *p = new Persona("Diana", 26);
cout << p->getNombre() << endl;

$ ./main
Diana

Crear un constructor en C++, existen 2 formas que si bien hacen lo mismo tienen diferente sintaxis.

Les dejo el codigó:

#include <iostream>
#include <string>

using namespace std;

class Person {
private:
  string name;
  int age;

public:
  Person(string n, int a) {
    name = n;
    age = a;
  }
  ~Person() { cout << "Destruction" << endl; }
  void say_hi() { cout << name << endl; }
};

int main() {
  Person p = Person("Zero", 14);
  p.say_hi();
}

les dejo algo que hice similar:

#include<iostream>
#include<string>
/*
ejemplo de encapsulacion automoviles
Dan Gallegos
*/
using namespace std;
class Automovil{
private:
string marca;
int ano;
public:
Automovil(string m,int a):marca(m),ano(a){}
~Automovil(){
cout<<“destructor”<<endl;
}
void prender(){
cout<<marca<<endl;
}
};
int main(){
Automovil *a=new Automovil(“nissan”,2010);
Automovil *a2=new Automovil(“toyota”,2019);

a->prender();
a2->prender();

}

Las palabras clave de control de acceso son: * `public` - Los miembros son accesibles desde cualquier parte del código. Esto significa que cualquier objeto o función puede acceder y modificar estos miembros * `private` - Los miembros solo son accesibles desde dentro de la misma clase. Esto ayuda a proteger los datos y a mantener la integridad de los mismos. * `protected` - Los miembros son accesibles desde la misma clase y desde las clases derivadas (subclases). Esto permite que las subclases accedan a ciertos datos o métodos de la clase base mientras los mantienen ocultos para otros usuarios.

El encapsulamiento es utilizado para esconder detalles de la puesta en práctica no importantes de otros objetos

Les dejo my code.

#include <iostream>
#include <string>

using namespace std;

class Persona {
private:
  string nombre;
  int edad;

public:
  Persona(string n, int e) {
    nombre = n;
    edad = e;
  }
  ~Persona() {
   cout<<"Destruction"<<endl; 
   			}
  void saludar() {
   cout <<nombre<<endl;
    }
};

int main() {
  Persona p= Persona("Sebas", 21);
  p.saludar();
}

Falto mencionar, que cuando el constructor de una clase se declara para recibir solamente un parametro, es recomendable declararlo como “explicit” para hacer que el constructor reciba solamente ese parametro con el tipo de datos definido y así evitar errores a la hora de pasar argumentos al constructor fuera de la clase, que no sean validos o no sean los esperados.