new int ???

What does the new keyword mean?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

class CRectangle {
    int *width, *height;
  public:
    CRectangle (int,int);
    ~CRectangle ();
    int area () {return (*width * *height);}
};

CRectangle::CRectangle (int a, int b) {
  width = new int;//this 
  height = new int;//this
  *width = a;
  *height = b;
}

CRectangle::~CRectangle () {
  delete width;
  delete height;
}

int main () {
  CRectangle rect (3,4), rectb (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}
http://www.cplusplus.com/doc/tutorial/dynamic/

However, let it be said that in this example it is a horrible idea to use dynamic allocation.
It means "make an object of this type in the heap memory space and give me back a pointer to it"

http://www.cplusplus.com/doc/tutorial/dynamic/
one thing i want to know.
1
2
3
4
width = new int;//the size of width in here is 4 cos it is an integer or bcoz it is a pointer?

//if we assign like below
width = new int[5];//the size of width is 5 right? I'm not sure about the correction of the code   
Last edited on
width is a pointer, so it will be the size of a pointer in both cases.
Thanks a lot :)
Topic archived. No new replies allowed.