what is -> in c++
The '->' Operator in C++
In C++, the '->' operator is used to access a member of a structure or class through a pointer. It is an alternative to the '.' operator, which is used to access members directly from an object or instance.
When using the '->' operator, the left-hand side operand must be a pointer to a structure or class, while the right-hand side operand is the member being accessed.
Here is an example to illustrate the usage of the '->' operator:
#include <iostream>
struct Person {
std::string name;
int age;
};
int main() {
Person* personPtr = new Person;
personPtr->name = "John";
personPtr->age = 25;
std::cout << "Name: " << personPtr->name << std::endl;
std::cout << "Age: " << personPtr->age << std::endl;
delete personPtr;
return 0;
}
In the above example, we define a structure called Person
with two members: name
and age
. We then create a pointer to a Person
object using the new
keyword. By using the '->' operator, we can access the members of the Person
object through the pointer. Finally, we delete the dynamically allocated object using the delete
keyword.
The '->' operator is particularly useful when working with dynamically allocated objects or when accessing members of objects through pointers.