Segmentation fault

Hi, I'm trying to work with a simple object that works great... with out pointers! As soon as I add the data members as pointers, the code will compile fine, but when I try to create an object I get a Segmentation fault error. I've read up on Segmentation fault and I'm not seeing how or why the objects constructor wouldn't have access to the memory? Do you have to make really different constructors when you're using pointer data members? Thanks!

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
*Program Name:  example.cc
*Discussion:    pointer data members
*Written by:    steven.riedel@gmail.com
*Compiler:      g++
*/

#include <iostream>
using namespace std;

class Point {  // very simple ( x, y ) object. 
public:

   Point( void ) {
     x = 0;
     y = 0;
   }

   Point( int arg1, int arg2 ) {

      x = arg1;
      y = arg2;

   }

   ~Point( void ) {

   }

   int getX( void ) {

      return x;

   }

   void setX( int arg ) {

      x = arg;
      return;

   }

   int getY( void ) {
   
      return y;

   }

   void setY( int arg ) {

      y = arg;
      return;

   }

protected:

   int x;
   int y;
};

class Square {  // contains a point and two measurements. 
                // that are evil points
public:

   Square( void ) {

     *anchor = Point( 0, 0 );
       // I read this as "Assign the value at the address of anchor to
       // the constructor of Point( int, int ) 
       // seems like it should work. 
     *length = 1;
       // I read this as "Assign the value at the address of length to 1. 
       // it doesn't like this either. 
     *width = 1;
   }

   ~Square( void ) {

      delete anchor;
      delete length;
      delete width;
   }

protected:
   Point* anchor;
   int* length;
   int* width;
};

int main( void ) {

   Square sqA;

   return 0;
}
You aren't allocating any member for your pointers inside your class, you seem to be assuming that the memory is made for you (which it isn't).

Instead of pointers, couldn't you just use normal variables?
OMG you're right. Oh I feel stupid now!!

I would need something like

1
2
3
4
5
6
7
8
9
Square( void ) {
   anchor = new Point( 0, 0 );
   length = new int;
      *length = 1;
   width = new int;
      *width = 1;

}


Thanks for the help! I could use normal variables, but this is for a homework assignment, and we are required to use all pointers for the data members. :)
Topic archived. No new replies allowed.