I have been playing around with C++ for awhile now and was wondering: what's the differnce between the [instance].[function] and [instance]->[function]? Does the dot notation just run the value and the arrow notation store value inside the instance?

Recommended Answers

All 5 Replies

They both do the same thing -- its just how the object is declared. The -> is pointer notation. Some examples:

class MyClass
{
public:
   int x;
 };

 // in this function pMyClass is a pointer, so it requires -> to 
 // reference any of it's objects
 void foo(MyClass* pMyClass)
 {
     pMyClass->x = 0;
 }   

 // in this function pMyClass is a reference which uses the . notation
 void foo(MyClass& pMyClass)
 {
     pMyClass.x = 0;
 }


 int main()
 {
    MyClass mc;
    mc.x = 0; // Neither a pointer nor a reference

    MyClass* pmc = &mc;
    pmc->x = 0; // This is a pointer and requires -> notation

    MyClass& rmd = mc;
    rmc.x = 0; // This is a reference so it requires . notation

Simply put, the dot (.) operator is used to access members of either a full instance or reference to and instance of an object. The pointer-to (->) operator is used to access members of a pointer to an instance. Ancient Dragon gave you some good examples.

Simply put, the dot (.) operator is used to access members of either a full instance or reference to and instance of an object. The pointer-to (->) operator is used to access members of a pointer to an instance. Ancient Dragon gave you some good examples.

So, the pointer itself utilizes the pointer-to operator, but when you're using a reference or not using pointers at all you use the operator?

I assume you mean "use the dot operator"... :-) If so, the answer is yes!

commented: Yes, sorry about that. Thank you. :-) +1

A slightly simpler explanation is that the arrow operator is syntactic sugar for accessing a member of a pointer to structure or class: p->member is equivalent to (*p).member. Since the latter is awkward to type and it's very common to have a pointer to a structure or class, the arrow operator was introduced as a syntactic convenience.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.