Language: EN

cpp-operadores-acceso

Access Operators in C++

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 Person {
public:
    std::string name;
    void greet() {
        std::cout << "Hello, I am " << name << std::endl;
    }
};

We can use the dot operator . to access the property name or the method greet().

Person person;
person.name = "Carlos";
person.greet(); // Prints: Hello, I am Carlos

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

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> names = {"Ana", "Luis", "Pedro"};

    std::string name = names[1];
    std::cout << name << std::endl; // Prints: Luis

    return 0;
}

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

Pointer Member Operator (->)

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

class Person {
public:
    std::string name;
    void greet() {
        std::cout << "Hello, I am " << name << std::endl;
    }
};

int main() {
    Person* person = new Person();
    person->name = "Carlos";
    person->greet(); // Prints: Hello, I am Carlos

    delete person;
    return 0;
}

In this example, the -> operator is used to access name and greet() through the pointer person.

Handling Smart Pointers

With the introduction of smart pointers in C++11, such as std::shared_ptr and std::unique_ptr, the -> operator is also used to access members of objects managed by these pointers.

#include <iostream>
#include <memory>

class Person {
public:
    std::string name;
    void greet() {
        std::cout << "Hello, I am " << name << std::endl;
    }
};

int main() {
    std::shared_ptr<Person> person = std::make_shared<Person>();
    person->name = "Carlos";
    person->greet(); // Prints: Hello, I am Carlos

    return 0;
}

In this case, person is a std::shared_ptr that manages a Person object, and the -> operator is used to access the members of the object.