I have found the class Kwadrat. The author used three types of operator ::, . and ->. The arrow is the one that only works. 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;
}
->
works on pointers, .
on objects and ::
on namespaces. Specifically:
- Use
->
or .
when accessing a class/struct/union member, in the first case through a pointer, in the latter through a reference.
- Use
::
to reference the function inside a namespace
or a class
(namespaces), for instance, when defining methods declared with the class.
x->y
is equivalent to (*x).y
. That is, ->
dereferences the variable before getting the field while the dot operator just gets the field.
x::y
looks up y in namespace x.
The -> is the equivalent of saying (*Kwadrat_pointer).value. You use it when you have an object pointer calling object methods or retrieving object members.
The . operator is used to access the methods and members in the object that is calling it (that is, the object on the left side of the ".").
The :: operator is called the scope operator. It tells your program where to look, for example when defining a class method outside of the class declaration.