Could somebody confirm...

the difference between . and ->

my understanding from a little play around is that . is for values and -> is for pointers?
Hi,

The dot is for public members (variables or functions) of a class or struct, the -> is the pointer to member (public variables or functions) operator. It was invented to save having to deference the pointer in order to get at the member.

Hope this helps a bit :+)
The dot is a member access operator for accessing public members.

If your variable is an object or structure you can use it to access the member variable and function

Now, we declare a class
1
2
3
4
5
class CBox
{
    public:
	int width,height,length;
};

in this example is equal to
1
2
3
4
struct CBox
{
    int width,height,length;
};

And we use the class in main
To create a CBox object named paperbox, and use dot operator
1
2
3
4
5
6
7
int main()
{
    CBox paperbox;
    paperbox.width  = 10;
    paperbox.height = 20;
    paperbox.length = 30;
}

Note that if your member is private in class, you can't access directly.

Let's show about -> operator
(when you're using -> operator, you just need to think that am I using a pointer variable or object?)
-> is an easy way to access the members of dereferenced object pointer.
Let's write some new code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CBox paperbox;
CBox *boxptr;

paperbox.width  = 10;
paperbox.height = 20;
paperbox.length = 30;
boxptr = &paperbox; //point to paperbox

//if we want to assign a new value to member variables in paperbox by pointer
//we have to dereference the pointer to object (from object pointer to object)
//and use dot operator to access the member variables

(*boxptr).width  = 15;
(*boxptr).height = 15;
(*boxptr).length = 15;

//these code is equivalent above 

boxptr->width  = 15;
boxptr->height = 15;
boxptr->length = 15;


As you could see the -> is a combined of the dereference and access operator
It's an easy way to access while you're manipulating a object pointer

Topic archived. No new replies allowed.