Question Trying to call a method in all objects of a particular class type

BruceJohnJennerLawso

Dread Lord of the Idiots
Addon Developer
Joined
Apr 14, 2012
Messages
2,585
Reaction score
0
Points
36
Hello everyone,

So Ive been teaching myself C++ lately. One of the things that I keep thinking would be really nice would be if I could call a given function in a class in all objects of that class type. The obvious advantage of this would be that I could take a vessel class and call its key functions (position, forces, rotation updates per frame) for any number of vessels in a simulation, including ones that get defined in sim via dynamic memory.

After a little bit of experimentation it dawned on me that I could do this with static member functions, so I added it to my little program that Im using to test various ways of working with classes. In the class of type B, I wrote it something like this:

Code:
#pragma once
#include "B.h"
#include "b.h"

class B
{	public:
	B(int i);
	B(void);
	int targetvalue;
	~B(void);		
	static void PlusPlus();		};

Code:
#include "B.h"
#include "b.h"


B::B(int i)
{	targetvalue = i;	}

B::B(void)
{	targetvalue = 0;	}

void B::PlusPlus()
{	targetvalue++;	}

B::~B(void)
{			}

I then proceeded to add this to int main()

Code:
B B_one(2);
	B B_two(4);
	B.PlusPlus();

And started to compile!!!

...at which point the compiler cuffed me on the back of the head & reminded me not to work with non-static members in static functions. :facepalm:

Any suggestions?
 
C++ does not track all objects of some type automatically. You could declare a set as a static member, and make the (de)constructor (un)register itself. Something like:

Code:
#include <set>

class B {
public:
    B (int x)
    {
        targetvalue = x;
        all_objects.insert (this);
    }

    ~B ()
    {
        all_objects.erase (this);
    }

    static void PlusPlus ()
    {
        std::set<B *>::iterator it = all_objects.begin(), end = all_objects.end();
        for (; it != end; it++)
            (*it)->targetvalue++;
    }

private:
    static std::set<B *> all_objects;
    int targetvalue;
};

NOT thread-safe.

EDIT: fix pointer deference
 
Last edited:
Back
Top