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 the 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;
}
};
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
In this example, the .
operator is used to assign a value to nombre
and to call the method saludar()
.
Index Operator ([])
The index operator ([]
) is used to access elements of arrays and collections that implement an index.
Accessing elements of a collection
#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;
}
In this case, the []
operator is used to access the second element of the vector nombres
.
Pointer Member Operator (->)
In C++ the pointer member operator (->
) is also used to access the 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;
}
In this example, the ->
operator is used to access nombre
and saludar()
through the pointer persona
.