1

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?

decypher
  • 251
  • 1
  • 2
  • 12
  • When using abstract classes and polymorphism, for one. – R_Kapp Nov 24 '15 at 21:46
  • Yeah, I bet that sample is laying the groundwork for a lesson on polymorphism. I'm sure the Rectangle class will inherit from a Shape class later on in the tutorial. – Mark Waterman Nov 24 '15 at 21:54
  • Consider yourself lucky for realizing that there is no point in using pointers when there is no need to (and be a bit patient until you encouter cases where you need them) – 463035818_is_not_a_number Nov 24 '15 at 22:00
  • Three things: 1) you are correct, there is no need to use pointers in this case. 2) The code example uses pointers in ways that are strongly against good practices (using smart pointers), so, this is a bad example of C++, 3) I think your question is legitimate – TheCppZoo Nov 24 '15 at 22:03

0 Answers0