top of page

What is the "-->" operator in C++?

The "-->" operator is a combination of two operators: the "->" operator and the "--" operator. The "->" operator is used to access a member variable or function of an object through a pointer to the object. The "--" operator is the decrement operator, which subtracts 1 from the value of a variable.


Therefore, when you see the "-->" operator in C++ code, it is likely being used to decrement a member variable of an object through a pointer. For example:

MyObject* ptr = new MyObject();
ptr-->member_variable--;

In this code, the "-->" operator is used to decrement the value of the member variable of the MyObject object pointed to by the pointer "ptr".


In C++, the "-->" operator is known as the pointer-to-member selection operator, and it is used to access a member of a structure or class using a pointer-to-member.


The syntax for the pointer-to-member selection operator is as follows:

objectPointer ->* memberPointer

Here, objectPointer is a pointer to an object, and memberPointer is a pointer to a member of that object. The operator returns the value of the member that is pointed to by memberPointer in the object that is pointed to by objectPointer.


Here's an example of how to use the pointer-to-member selection operator (-->) in C++:

#include <iostream>using namespace std;

class MyClass {
public:
    int x;
    int y;
    void print() {
        cout << "x: " << x << ", y: " << y << endl;
    }
};

int main() {
    MyClass obj;
    MyClass* ptr = &obj;
    int MyClass::* ptr_x = &MyClass::x;
    int MyClass::* ptr_y = &MyClass::y;

    ptr->*ptr_x = 10;
    ptr->*ptr_y = 20;

    ptr->print();

    return 0;
}

In this example, we define a MyClass class that has two integer members x and y, and a print() method that prints the values of these members to the console.


We create an instance of the class obj and a pointer ptr that points to this instance.

We also create two pointers-to-member ptr_x and ptr_y that point to the x and y members of MyClass, respectively.


Next, we use the pointer-to-member selection operator --> to assign values to the x and y members of the obj object via the ptr pointer.


Finally, we call the print() method of the obj object to print the values of x and y to the console.

Output:

x: 10, y: 20

In this example, the --> operator is used to access the x and y members of the obj object using the ptr pointer and the pointers-to-member ptr_x and ptr_y.

0 comments
bottom of page