Home > Backend Development > C++ > Dot (.) vs. Arrow (->) Operators in C : When to Use Which?

Dot (.) vs. Arrow (->) Operators in C : When to Use Which?

DDD
Release: 2025-01-04 02:23:40
Original
883 people have browsed it

Dot (.) vs. Arrow (->) Operators in C  : When to Use Which?
) Operators in C : When to Use Which? " />

Understanding Dot (.) and Arrow (->) Operators in C

The dot (.) operator and arrow (->) operator are both used in C to access members of classes and structs. However, there are some key differences between the two.

Usage:

  • Dot (.) operator: Used with objects to directly access class members.
  • Arrow (->) operator: Used with pointers to objects or to access virtual functions.

Relationship:

  • foo->bar() is equivalent to (*foo).bar().

Parentheses:

  • Parentheses around foo are required because the dot operator has higher precedence than the dereference operator .

Overloading:

  • Dot operator cannot be overloaded.
  • Arrow operator can be overloaded.

Pointers:

  • Dot operator cannot be applied to pointers.
  • Arrow operator can be applied to pointers to access members of a class or struct.

Example:

class MyClass {
    public:
        int x;
};

int main() {
    MyClass obj;
    obj.x = 10;  // using dot operator

    MyClass* ptr = &obj;
    ptr->x = 15;  // using arrow operator
}
Copy after login

In this example, the dot operator is used to access the x member of the obj object. The arrow operator is used to access the x member of the ptr pointer.

The above is the detailed content of Dot (.) vs. Arrow (->) Operators in C : When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template