Reputation: 351
Is there any way how can I share one variable (object of class) over more instances of another class? Static member is not what I am looking for. I know that one variable (large object) will be shared among more instances (but not all of them). How can I do that in C++? Thanks for any help.
Example:
class ClassA {
public:
...
private:
ClassB object; // this variable will be shared among more instances of ClassA
}
Upvotes: 1
Views: 6124
Reputation: 998
use static variable:
class ClassA {
public:
...
private:
static ClassB *object; // this variable will be shared among more instances of
}
ClassB * ClassA::object = nullptr;
ClassA::ClassA()
{
if (object == nullptr)
object = new ClassB();
}
Upvotes: 0
Reputation: 1
I think std::shared_ptr might be what you want. In that case your code would be something like that:
class ClassA {
public:
...
private:
std::shared_ptr<ClassB> object; // this variable will be shared among more instances of ClassA
}
But you will need to define where that pointer is instantiated, that depends on your needs. Maybe you could provide more context to your question like:
Upvotes: 0
Reputation: 111
You could use pointers.
class B { ... }
class A {
...
B *b;
...
}
main() {
A a1, a2;
B *b1 = new B();
a1.b = b1;
a2.b = b1;
}
That way b
member on both a1
and a2
reference the same object.
Upvotes: 0
Reputation: 170084
Well, you'll need to move the member out of the class, and store a pointer instead. You'll also need to count the instances that refer to that independent object. That's a lot of work, but fortunately the C++ standard library has you covered with std::shared_ptr
:
class ClassA {
public:
// ...
private:
std::shared_ptr<ClassB> object; // this variable will be shared among more instances of ClassA
};
Upvotes: 6