1

I'm fairly new to C++.

Going through some existing C++ code, I've seen :: , . , and -> operators used. The question is, what is the difference between them and when would you use one or the other?

I've seen the :: operator on occasion in C#, but I always use . to access members, implicitly declaring the scope. Assuming those two are the equivalents in C++, I'm still not sure why we use the arrow -> operator and why it seems to be used interchangeably with the dot . operator.

Thanks.

raybarrera
  • 160
  • 1
  • 10

1 Answers1

1

:: is the scope operator. It is used to state which scope you are in:

// in the A.h file
class A
{
public:
    A();
    void foo();
};

// in the A.cpp file
#include "A.h"

A::A() // the scope of this function is A - it is a member function of A
{

}

void A::foo() // same here
{

}

void bar() // as written, this function is in the global scope ::bar
{

}

The . operator is used to access members of a "stack" allocated variable.

A a; // this is an automatic variable - often referred to as "on the stack"
a.foo();

The -> operator is used to access members of a something that is pointed to (either heap or stack).

A* pA = new A;
a->foo();
A a;
A* pA2 = &a;
pa2->foo();

It is equivalent to (*pA).foo(). C# does not have the concept of an automatic variable, so it has no need for a dereferencing operator (which is what *pA and pA-> are doing). Since C# treats pretty much everything like it is a pointer, the dereferencing is assumed.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42