P.N.
P.N.

Reputation: 351

C++ sharing one variable among more instances of object

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

Answers (4)

Cool Goose
Cool Goose

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

MarxNotDead
MarxNotDead

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:

  • Where does ObjectB come from, is it owned by another entity?
  • How is it distributed to the instances of ObjectA?

Upvotes: 0

freddieRV
freddieRV

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

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

Related Questions