Joe
Joe

Reputation: 538

C++ When do I use -> or ::

I know that in C++, you use either -> or :: instead of . in language such as C# to access object's values, e.g. button->Text or System::String^, but I don't know when I should use -> or ::, and it is very frustrating as it causes me many compiler errors. I would be very grateful if you could help. Thanks :)

Upvotes: 3

Views: 274

Answers (5)

Tony The Lion
Tony The Lion

Reputation: 63190

-> is when you are accessing the member of a pointer variable. EG: myclass *m = new myclass(); m->myfunc(); Calls myfunc() on pointer to myclass. :: is the scoping operator. This is to show what scope something is in. So if myclass is in namespace foo then you'd write foo::myclass mc;

Upvotes: 10

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

Opertor -> is applied when the left operand is a pointer. Consider for example

struct A
{
   int a, b;
   A( int a, int b ) : a( a ), b( this->a * b ) {}
};

Operator :: referes to the class or anmespace for which the right operand belongs. For example

int a;

strunt A
{
   int a;
   A( int a ) { A::a = a + ::a; }
};

The period is used then the left operand is lvalue of an object. For example

struct A
{
   int x;
   int y;
};

A *a = new A;

a->x = 10;
( *a ).y = 20;

Upvotes: 2

crashmstr
crashmstr

Reputation: 28563

Contrary to what your question states, you do use . in C++. Quite a bit.

. (used with non-pointers to access members and methods)

std::string hello = "Hello";
if (hello.length() > 3) { ... }

-> (used with pointers to access members and methods)

MyClass *myObject = new MyClass;
if (myObject->property)
    myObject->method();

:: (scope resolution)

void MyClass::method() { ... } //Define method outside of class body

MyClass::static_property; //access static properties / methods

:: is also used for namespace resolution (see first example, std::string, where string is in the namespace std).

Upvotes: 4

masoud
masoud

Reputation: 56479

I try to show an examples of some usages of ::, . and ->. I hope it helps:

int g;

namespace test
{

  struct Test
  {
     int x;
     static void func();
  };

  void Test:: func() {
     int g = ::g;
  }

}

int main() {

  test::Test v;
  test::Test *p = &v;

  v.x = 1;
  v.func();
  p->x = 2;
  p->func();

  test::Test::func();

}

Upvotes: 3

Johny
Johny

Reputation: 1997

  • -> if you have pointer to some object this is just shortcut for dereferencing that pointer and accessing its attribute.

    pointerToObject->member is the same as (*pointerToObject).member

  • :: Is for access stuff from some scope - it works only on namespaces and class/struct scopes.

    namespace MyNamespace {
      typedef int MyInt;
    }
    MyNamespace::MyInt variable;
    

Upvotes: 4

Related Questions