I have searched the internet over and asked around for a good explanation of the difference between the following symbols in C++: -> , * , and & . I have a vague concept of each (I use them occasionally), but nothing concrete. Can someone please explain this to me in uncomplicated terms, possibly with an example of the appropriate use of each? I would greatly appreciate it!
Pointer Help
Let's start with &.
& is the "get address" operator. This turns something (like, say, an int) into a pointer to that something:
Now, suppose the thing we're pointing to is a class or structure. Then I can use -> as a shorthand for (*pointer).member, like this:
& is the "get address" operator. This turns something (like, say, an int) into a pointer to that something:
int value = 42;
int * pointer = &value;
Now that we have a pointer, we need a way to find out what it points at. That's where * comes it - it's like the reverse of &. I like to think of it as "follow":int newValue = *pointer;
Note that I can either read from or write to the result of dereferencing a pointer:*pointer = 33;
Now, suppose the thing we're pointing to is a class or structure. Then I can use -> as a shorthand for (*pointer).member, like this:
struct Foo {
int Number;
bool Flag;
};
Foo obj;
obj.Number = 42;
obj.Flag = true;
Foo * pointer = &obj;
pointer->Flag = false;
// Exactly the same effect:
(*pointer).Flag = false;
Note that in C++ you can use -> in more complex ways, but that can come later. In general there's a lot of stuff possible with pointers, but hopefully those few basic elements will get you started!
it helps a lot to write a small program which has a variable, set it then printfs each of the options to the output. Then nose at the debugger for the value, the location etc, get your head around it properly.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement