'How do I call a method for all objects in a class?
I want to call a method for all objects in a class at once. What's the simplest way to do that?
Also, how do I call a method for some, but not all objects in a class?
Solution 1:[1]
You could do something like this. The object constructor puts the object pointer into a set and the destructor removes them from the set. The set contains pointers to all living objects.
It's pretty self explanatory:
#include <iostream>
#include <set>
class Foo
{
static std::set<Foo*> FooObjects; // set of all Foo objects
int value = 0;
void Register(Foo*);
void UnRegister(Foo* f);
public:
Foo();
Foo(int v);
~Foo();
static std::set<Foo*>& FooSet();
void Display();
void Multiply(int multiplicator);
};
std::set<Foo*> Foo::FooObjects;
std::set<Foo*>& Foo::FooSet()
{
return FooObjects;
}
void Foo::Register(Foo* f)
{ // register an object
FooObjects.insert(f);
}
void Foo::UnRegister(Foo* f)
{
// unregister an object
FooObjects.erase(f);
}
Foo::~Foo()
{
UnRegister(this);
}
Foo::Foo()
{
Register(this);
}
Foo::Foo(int value) : value(value)
{
Register(this);
}
void Foo::Multiply(int multiplicator)
{
value *= multiplicator;
}
void Foo::Display()
{
std::cout << "Foo: " << value << "\n";
}
void SomeFunction()
{
Foo farray[10];
}
int main()
{
Foo f1;
Foo F2(2);
Foo F3(3);
SomeFunction(); // 10 Foo objects are created in SomeFunction
// but they are destroyed right after and therefore
// they never show up below.
// Display all Foo objects
for (const auto& object : Foo::FooSet())
object->Display();
// Multiply all foo objects by 2
for (auto& object : Foo::FooSet())
object->Multiply(2);
std::cout << "\n";
// Display all Foo objects
for (const auto& object : Foo::FooSet())
object->Display();
}
Possible output:
Foo: 3
Foo: 2
Foo: 0
Foo: 6
Foo: 4
Foo: 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
