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

Digital Marketing Facebook Marketing API 3 years ago

8.52K 0 0 0 0

_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?

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (0)

Post Answer

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.

Similar Forum


Q

What are the best SEO tools for a personal website? What website or tools should I use to build and...

What are the best SEO tools for a personal website? What website or tools should I use to build and...
Q

Why is keyword research important?

Why is keyword research important?
Q

What is SEO ?

What is SEO ?