George
George

Reputation: 3030

C++ static vector of objects inside Object contstructor access?

I want a static vector inside Object that stores pointers to every Object ever constructed so I can run a loop through every Object.

//Object.h
public:
  Object();
  stuff();
  static vector<Object*> objects;

//Object.cpp
vector<Object*> Object::objects;
Object::Object(){ objects.push_back(this); }
Object::stuff(){ /*Do stuff*/ }

Is this correct?

I want this to work:

//ObjectB.cpp
Object::objects[0]->stuff();

When I run it, I'm getting "Access violation reading location 0xCCCCCCCC" error.

Upvotes: 1

Views: 1386

Answers (2)

LeleDumbo
LeleDumbo

Reputation: 9340

Object.h:

#ifndef OBJECT_H
#define OBJECT_H

#include <vector>

using namespace std;

class Object {
public:
  Object();
  void stuff();
  static vector<Object*> objects;
};

#endif // OBJECT_H

Object.cpp:

#include "Object.h"
#include <iostream>

using namespace std;

vector<Object*> Object::objects;

Object::Object() {
  objects.push_back(this);
}

void Object::stuff() {
  cout << "Stuff from object" << endl;
}

ObjectB.cpp:

#include "Object.h"
#include <vector>

using namespace std;

int main() {
  Object a,b,c;

  // this loop should run 3 times, as many as Object instance created
  for (vector<Object*>::iterator it = Object::objects.begin(); it != Object::objects.end(); it++) {
    (*it)->stuff();
  }
  return 0;
}

Is that what you want?

Upvotes: 1

FBForecomm
FBForecomm

Reputation: 11

Assuming "ObjectB" class inherits the "Object" class, your Object.h and Object.cpp are OK.

// Object.h
static vector<Object*> objects; // [Is this correct?][1]

-> OK, static member declaration

// Object.cpp
vector<Object*> Object::objects; // [Is this correct?][1]

-> OK, static member initialisation (in your cpp file)

// Object.h
vector<Object*> Object::objects; //[error C2838][2]

-> This is not right, I assume ObjectB inherits Object, you don't have to declare that. To refer to your static member, you just have to do "Object::objects". Do not forget to call your Object constructor from your ObjectB constructor, otherwise your ObjectB instance will not be added to your Object::objects vector :

// ObjectB.cpp
ObjectB() : Object() // Calling Object() will add your instance to "objects" vector
{
  ...
}

Then :

Object::objects.stuff(); // or with ->, i.e. Object::objects->stuff()

-> This should work (if you do not forget to call Object constructor from your ObjectB constructor).

To the question "is there another way to keep track of all your objects", well, it depends on what you are trying to achieve.

Upvotes: 1

Related Questions