feelfree
feelfree

Reputation: 11753

In C++ how to share common elements within the same class objects.

I give the following example to illustrate my question:

class A
{
  public:
       int common;
       int a,b,c;
        A(int _common, int _a, int _b, int _c):common(_common),a(_a),b(_b),c(_c)
        {

         }
};
A obj1, obj2, obj3, obj4;

class B
 {
  public:
     void push_back(int common, int a, int b, int c)
     {
        A obj(common,a,b,c);
        aObjArray.push_back(obj);
      }
     std::vector<A> aObjArray_;

};


  B myObj;
  int common=3;
   myObj.push_back(common,1,2,4);
   myObj.push_back(common,4,26,54);
   myObj.push_back(common,7,52,64);

In this example, class B contains an array of Class A object. Creating A object is determined by four elements. Expect the common element in class A, other elements will be different for each generated A object. One solution I can think of is to make common element a static class member, so that several A class objects will share the same.

class A
{
public:
   static int common;
   A (int _a, int _b, int _c)
   {...}

}

class B
{ 
public
   int common;
    B()
    {
        A::common = common;

     }

}

Any other ideas?

Upvotes: 1

Views: 342

Answers (2)

justin
justin

Reputation: 104698

There are many approaches to accomplish this, so a specific example will likely provide you with better answers.


One easy approach to simplifying your program is to introduce a variable into class B which defines the value for common when constructing A. Specifically, this value would be read in B::push_back and the caller would only need to provide a,b,c.


If the value of common is known at compilation, you can consider making class A a template:

template<int common>
class A {
public:
  void foo() {
    ...`common` available here...
  }
};

For a complex or mutating object, you might consider using a shared pointer. Typically, that complexity can (and should) be avoided.

Upvotes: 1

W.F.
W.F.

Reputation: 13988

Maybe shared pointer would do the trick for you?

#include <vector>
#include <memory>
#include <iostream>

struct A {
   std::shared_ptr<int> common;
   int a, b, c;
   void use_common() {
      std::cout << *common << std::endl;
   }

};

int main() {
   std::vector<A> va;
   auto common = std::make_shared<int>(1);
   va.push_back({common, 1, 2, 3});
   va.push_back({common, 4, 5, 6});
   va.push_back({common, 7, 8, 9});
   va[0].use_common();
}

Upvotes: 1

Related Questions