views:

87

answers:

5

Looking at example under "Pointers to classes" (very bottom)

How is it that we can use the dot operatior here:

CRectangle * d = new CRectangle[2];
...
d[1].set_values (7,8);

if d is a pointer?

Same question for the lines:

  cout << "d[0] area: " << d[0].area() << endl;
  cout << "d[1] area: " << d[1].area() << endl;

Also, For the declaration:

  CRectangle * d = new CRectangle[2];

We can just declare a pointer to the type without declaring an object first?

+3  A: 

d is a pointer to an array of CRectangle objects (2 in this case). d[i] is the i'th CRectangle object. so when you say d[i].set_values(), you are really calling the set_values method on the i'th CRectangle object in that array.

cw22
new question, about accepted answer: If d is just a pointer to an array of objects, how is it that we can index a single pointer with d[0], d[1], etc?
Tommy
Because pointers and arrays are essentially the same thing in c++. your array of CRectangle is just two instances of CRectangle one after the other in memory. The compiler knows how large a CRectangle is, so when you use d[1] it adds the size of one CRectangle to the memory address stored in d, and then derefrences the result.d[1] is the same thing as *(d+1)d[0] is the same thing as *(d+0), which is also the same as *d
Alan
+3  A: 

In this case, the pointer is actually an array, with two objects in it's construction. First "d" is constructed as an array with 2 elements:

CRectangle * d = new CRectangle[2];
// which is the dynamically allocated version of..
CRectangle d[2];

Then, it accesses the 2nd element's area() method via:

d[1].area()
marshall_law
+1  A: 
  1. The '.' is used as opposed to the de-reference '->' because while d is a pointer the objects to which it points are indeed not pointers, thus the d[1] returns a non-pointer object which is 'local'.
  2. The new operator in this sense works because the CRectangle class has a default constructor, however in the case where no default constructor is available this is not possible. What happens is new allocates space for two rectangle objects each of which is constructed via their default constructor.
DeusAduro
+3  A: 

In your example, while d is indeed a pointer, d[1] is not. It is a reference to the object at *(d+1).

Greg Hewgill
+1  A: 

Thought I'd just add the case where you would use the '->' operator:

CRectangle* d[2];
d[0] = new CRectangle();
d[1] = new CRectangle();
d[0]->set_values(7,8);
Jason
so your example is an array of pointers instead?
Tommy
you could also do this (from memory) if you wanted a dynamic size: CRectangle ** d = new CRectangle*[x];
Lodle
yeah, it's an array of pointers.
Jason