I don't understand the point of pointers to classes [duplicate]

Digital Marketing Facebook Marketing API . 2 years ago

  0   0   0   0   0 tuteeHUB earn credit +10 pts

5 Star Rating 5 Rating
_x000D_ _x000D_ _x000D_ This question already has an answer here:_x000D_ _x000D_ _x000D_ Why should I use a pointer rather than the object itself?_x000D_ _x000D_ 21 answers_x000D_ _x000D_ _x000D_ _x000D_ _x000D_ I was reading through C++ tutorial and came across this example code. // pointer to classes example #include using namespace std; class Rectangle { int width, height; public: Rectangle(int x, int y) : width(x), height(y) {} int area(void) { return width * height; } }; int main() { Rectangle obj (3, 4); Rectangle * foo, * bar, * baz; foo = &obj; bar = new Rectangle (5, 6); baz = new Rectangle[2] { {2,5}, {3,6} }; cout << "obj's area: " << obj.area() << '\n'; cout << "*foo's area: " << foo->area() << '\n'; cout << "*bar's area: " << bar->area() << '\n'; cout << "baz[0]'s area:" << baz[0].area() << '\n'; cout << "baz[1]'s area:" << baz[1].area() << '\n'; delete bar; delete[] baz; return 0; } So the address of obj (&obj) is assigned to foo, then by using foo->area(), one can calculate foo's area. But why go through all that trouble? What benefit does foo pointer offer? Because to me, it seems like simply instantiating foo just by Rectangle foo and using foo.area() to calculate the area is easier. But when would you use Rectangle *foo and the address to do the same thing?

Posted on 16 Aug 2022, this text provides information on Facebook Marketing API related to Digital Marketing. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Write Your Comments or Explanations to Help Others



Tuteehub forum answer Answers (0)


No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

tuteehub community

Join Our Community Today

Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.

tuteehub community