Possible Duplicate:
When do I use a dot, arrow, or double colon to refer to members of a class in C++?
I have created the class called Kwadrat and I have three int fields inside. The Code Blocks gives me advice that i can get into the field of the object by ::
, .
and ->
. The arrow is the one that only works, but why? What's the difference between those three?
#include <iostream>
using namespace std;
class Kwadrat{
public:
int val1, val2, val3;
Kwadrat(int val1, int val2, int val3)
{
this->val1 = val1;
//this.val2 = val2;
//this::val3 = val3;
}
};
int main()
{
Kwadrat* kwadrat = new Kwadrat(1,2,3);
cout<<kwadrat->val1<<endl;
cout<<kwadrat->val2<<endl;
cout<<kwadrat->val3<<endl;
return 0;
}
1.->
for accessing object member variables and methods via pointer
to object
Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();
2..
for accessing object member variables and methods via object instance
Foo foo;
foo.member_var = 10;
foo.member_func();
3.::
for accessing static variables and methods of a class/struct
or namespace
. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)
int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();