I was reading through C++ tutorial and came across this example code.
// pointer to classes example
#include <iostream>
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?