cpp-operadores-acceso

Access Operators in C++

  • 2 min

Access operators in C++ allow us to access members of classes and structures (their variables and methods) or elements of collections.

Dot Operator .

The dot operator (.) is the most common access operator in C++. It is used to access members of a class or structure (including properties, methods, and fields).

For example, if we have this class:

class Persona {
public:
    std::string nombre;
    void saludar() {
        std::cout << "Hola, soy " << nombre << std::endl;
    }
};
Copied!

We can use the dot operator . to access the property nombre or the method saludar().

Persona persona;
persona.nombre = "Carlos";
persona.saludar(); // Prints: Hola, soy Carlos
Copied!

In this example, the . operator is used to assign a value to nombre and to call the saludar() method.

Index Operator []

The index operator ([]) is used to access elements of arrays and collections that implement an index.

#include <iostream>
#include <vector>

int main() {
    std::vector<std::string> nombres = {"Ana", "Luis", "Pedro"};

    std::string nombre = nombres[1];
    std::cout << nombre << std::endl; // Prints: Luis

    return 0;
}
Copied!

In this case, the [] operator is used to access the second element of the nombres vector.

Pointer-to-member Operator ->

In C++, the pointer-to-member operator (->) is also used to access members of an object through a pointer.

class Persona {
public:
    std::string nombre;
    void saludar() {
        std::cout << "Hola, soy " << nombre << std::endl;
    }
};

int main() {
    Persona* persona = new Persona();
    persona->nombre = "Carlos";
    persona->saludar(); // Prints: Hola, soy Carlos

    delete persona;
    return 0;
}
Copied!

In this example, the -> operator is used to access nombre and saludar() through the persona pointer.