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.