How do I read this tutorial code line?

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>
using namespace 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.
Last edited on
closed account (SECMoG1T)
new is used to allocate memory dynamically, you might want to check the link below for a clear description.

https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory/
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.
Last edited on
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.
My bad. I guess I wasn't paying enough attention when I read the "new" section. I will have to reread it.
closed account (E0p9LyTq)
CRectangle rect[2]; creates a two element array of class CRectangle on the stack.

CRectangle* rect = new CRectangle[2]; creates a two element array of class CRectangle on the heap (aka the "free store").
Topic archived. No new replies allowed.