-2

I Was just confused on the part of using a pointer on C++.. well you might say, "a pointer is obviously a memory adress of another variable and there are certaintly conditions in your program where you will need them". But i dont mean pointer in general, i mean the pointer you use to like "simulate" a class... I think code will explain it more:

#include <iostream> #include <string> #include "Book.h" int main() { Book book1; Book *bookPointer = &book1; book1.setBooksId(123); std::cout << "BOOK ID: " << book1.getBookId() << std::endl; (*bookPointer).setBooksId(300); std::cout << (*bookPointer).getBookId() << std::endl; /*When usage of arrow member selection member, left is always a pointer. Same thing as above, but better practice! */ bookPointer->setBooksId(100); std::cout << "POINTER ARROW : " << bookPointer->getBookId() << std::endl; return 0; } 

Here you see i have another pointer that is called bookPointer which all it does is the same as the original instance of book class book1... I dont get it.. What is the advantage of using this? Give me a scenario if you can! Thanks for Helping!!

1
  • There is indeed no benefit in the use you have in your example code. But look at the accepted answer to the question linked to by Phil. The answer lists the scenarios where pointers (or references) actually must be used. Commented Apr 21, 2016 at 19:33

1 Answer 1

1

There is no "simulation" happening at all. book1 has an address too, and the this pointer is set to the address of book1 when you do book1.setBooksId(123);. There is no difference.

Sign up to request clarification or add additional context in comments.

11 Comments

There is a diffrence according to this: stackoverflow.com/questions/22146094/…
@AmanuelBogale Yeah? Where?
The Anwsers i think.. The First Anwser? I Cant see his position on this topic
@AmanuelBogale The this pointer is just a hidden parameter in the call to the method. Whether the pointer is read from a pointer variable (foo->bar()), or inferred by taking the address of a variable (foo.bar()), at the end of the day, it passes a pointer to the method.
@AmanuelBogale If you are being that vague, why not say it is on the internet?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.