Memory distance between objects of the classes

Hello!
I have played with pointers to classes, and got this result forobject's addresses:


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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  #include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
};

class Rectangle: public Polygon {
  public:
    int area()
      { return width*height; }
};

class Triangle: public Polygon {
  public:
    int area()
      { return width*height/2; }
};

int main () {
  Rectangle rect;
  Rectangle recta;
  Rectangle rectaa;
  Rectangle rectaaa;
  Triangle trgl;
  Polygon * ppoly1 = &rect;
  Polygon * ppoly1a = &recta;
  Polygon * ppoly1aa = &rectaa;
  Polygon * ppoly1aaa = &rectaaa;
  Polygon * ppoly2 = &trgl;
  ppoly1->set_values (4,5);
   ppoly1a->set_values (10,20);
  ppoly1aa->set_values (100,200);
  ppoly1aaa->set_values (7,4);
  ppoly2->set_values (4,5);
  cout << rect.area() << '\n';
  cout << recta.area() << '\n';
  cout << rectaa.area() << '\n';
  cout << rectaaa.area() << '\n';
  cout << trgl.area() << '\n'<<'\n';
  cout << ppoly1<<endl;
  cout << ppoly1a<<endl;
  cout << ppoly1aa<<endl;
  cout << ppoly1aaa<<endl;
  cout << ppoly2<<endl;
  return 0;
}


20
200
20000
28
10

0xff8df078
0xff8df070
0xff8df068
0xff8df060
0xff8df058


My question is what is the reason that the memory distance is like:
8-2-8-2

What causes that the distance has right that value? Is that important, or just coincidental?

Many thanks!!!
the distance is actually 8-8-8-8
Note that the addresses are printed out in hexadecimal form.

1 Byte is allways 8 bit and 1 Byte is the smallest addressable unit.
Do address 1 Byte in your memory you have a pointer, this pointer has to be able to point to all locations in your RAM, if you have a 32-bit system the size of a pointer is 32-bit (or 4 Byte).

In your case you work on a 64-bit environment, therefore the size of a pointer is 64 bit (or 8 Byte) so the distance between your pointers should be 8 byte (if no other memory is allocated on stack between those blocks)
Last edited on
O sure, many thanks!!!
ps. what, if the object is simply too big ? What happens then?
When you allocate an object that's to big on the heap an exception of type std::bad_alloc is thrown.
Many thanks!!!
Topic archived. No new replies allowed.