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
#include
#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!!
Answer
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.
No comments:
Post a Comment