Joel Shook
Joel Shook

Reputation: 9

I assign a pointer and it nulls itself out

So I have a constructor for an object, that on creation sets a few values and then places itself at the end of a linked list.

The problem I'm having is that when it assigns the address of the new object to the head or tail of the list, it assigns, leaves the constructor and for some reason the head and tail both get reset to 0.

Object Object1("OddJob", 2, 2, 9);

calls constructor

Object::Object(string label, float x, float y, float z)
{
  x_ = x;
  y_ = y;
  z_ = z;
  if(label == "")
  {
    label = "Object";
  }
  label_ = label;
  if(headObject == 0)
  {
    headObject = this;
    tailObject = this;
  }
  else
  {
    tailObject->next = this;
    tailObject = this;
  }
  next = 0;
}

Edit: headObject and tailObject are globals declared in a .h file. They are declared as:

static Object * headObject;
static Object * tailObject;

Upvotes: 0

Views: 100

Answers (2)

Goz
Goz

Reputation: 62323

Either declare the headObject and tailObject as static members of the Object class.

class Object
{
    static Object* headObject;
    static Object* tailObject;
    // Rest of class.
}

Not forgetting to define them in the Object.cpp as follows:

Object* Object::headObject = nullptr;
Object* Object::tailObject = nullptr;

Or define them as "extern" in the header:

extern Object* headObject;
extern Object* tailObject;

and then define them in the Object.cpp:

Object* headObject = nullptr;
Object* tailObject = nullptr;

Otherwise you are essentially defining them in every cpp file that includes the .h. The static simply says to each of those files that they have their own version of those variables that are distinct from each other. Thus headObject in main.cpp is not the same as headObject in Object.cpp. Do not confuse class statics and non class statics. The linker error you see without the static is explaining what the problem is. If you get such a link error look it up and try and learn WHY you are getting it otherwise you will make hard to track down errors like you are seeing.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110668

The use of static on a global object causes it to have internal linkage. This means that each translation unit that includes your header will have its own version of headObject and tailObject.

Instead, you should declare them as extern in the header file:

extern Object * headObject;
extern Object * tailObject;

Then in a single translation unit (typically the .cpp corresponding to that .h), you should give the definitions as:

Object * headObject;
Object * tailObject;

You can't just define them like this in the header file, otherwise you'll break the one definition rule when you include the header in multiple files.

Upvotes: 3

Related Questions