I'm having trouble reading one of the code examples from the Classes section of this website's tutorial pdf. My problem is on line 16:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// pointer to classes example
#include <iostream>
usingnamespace std;
class CRectangle {
int width, height;
public:
void set_values (int, int);
int area (void) {return (width * height);}
};
void CRectangle::set_values (int a, int b) {
width = a;
height = b;
}
int main () {
CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];
...
I see that a pointer to objects of type CRectangle is being created, but the value that is assigned to it doesn't make any sense to me. The keyword "new" is confusing me because I don't know what new object is being created. Does the "new" refer to the pointer "d", despite it's place after the assignment operator? Or is "CRectangle[2]" some kind of new object being declared (without an identifier??) I just don't know what anything after that assignment operator means.
Since d is a CRectangle pointer, I would assume that it can only be assigned the address of a CRectangle object, and "new CRectangle[2]" doesn't look like an address at all. It doesn't look like anything I can recognize.
I've read the section on "new" and have a basic understanding of what it is. What I don't understand is what it's doing here.
What I've seen up to now are declarations like: "new int number" or "new CRectangle bobTheRectangle" where new is followed by a type and then by an identifier. That isn't the case here, so I can't tell what object is being created with new.
Additionally I don't understand what "CRectangle[2]" means because CRectangle is a class, not a pointer/array.
What I've seen up to now are declarations like: "new int number" or "new CRectangle bobTheRectangle" where new is followed by a type and then by an identifier.
In this case you've been looking at syntax errors.