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 :)
C++ When do I use -> or ::
242 Views Asked by Joe AtThere are 5 best solutions below
On
-> 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;
On
->if you have pointer to some object this is just shortcut for dereferencing that pointer and accessing its attribute.pointerToObject->memberis 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;
On
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).
On
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;
I try to show an examples of some usages of
::,.and->. I hope it helps: