I'm bit new to C++ and try to work things with Qt and came across this confusing thing:
The concepts on various tutorials state something like:
Class *obj;
*obj
- will display the value of object stored at the referenced memory
obj
- will be address of memory to which it is pointing
so, I would do something like
*obj=new Class();
but if I want to access a function, I have to do obj->function1();
instead of *obj->function1();
-- not sure why, since with normal objects [ normalObj.function1();
] would work, since that's the value directly.
So, for pointer objects why do we use memory reference to access the function, or is it that in case of normal objects also, its always references
P.S: Can someone guide me to a good tutorial of usage of pointers in C++, so that my queries like these can be directly addressed in it.
The
*
symbol is used to define a pointer and to dereference a pointer. For example, if I wanted to create a pointer to an int, I could do:int *ptr;
In this example, the
*
is being used to declare that this is a pointer to an int. Now, when you are not declaring a pointer and you use the*
symbol with an already declared pointer, then you are dereferencing it. As you probably know, a pointer is simply an address. When you dereference a pointer, you are obtaining the value that is being pointed to by that address. For example:This will print out 5. Also, if you are assigning a pointer to a new address and it's not in the declaration, you do not use the
*
symbol. So:is how you would do it. You can also deference the pointer to assign a new value to the value being pointed to by the address. Such as:
Now,
->
acts like the deference symbol. It will dereference the pointer and then use the member functions and variables as if you had used.
with a non-pointer object. Even with an object that is not a pointer you can use the->
by first getting the address:That's just a brief overview of pointers, hope it helps.
Actually, you're wrong. You do:
or
which are completely different.
wouldn't compile.
obj
is of typeClass*
, so that's what you can assign to it (and whatnew Class
returns).More precisely u can do like this
You can use the "normal"
.
to access the objects members, but you have to dereference the pointer first.Due to operator precedence, this will look like
(*obj).member
. For those who think this is too much to write,obj->member
is a shorter alternative.If you have an object
c
of typeClass
,*c.ptr
means dereferencing a pointerptr
that is a member ofClass
. That is one reason for(*obj).member
, which means something else.