Solved

How to define Global structure shared by 2 classes?

Posted on 2012-03-11
9
343 Views
Last Modified: 2012-03-17
Want to have a global data structure which can be shared by several classes or shared by several files. If the data structure in one of classes is updated, the other classes can use the same updated data in their own classes.  A workable code snippet is highly appreciated.
0
Comment
Question by:jl66
  • 3
  • 2
  • 2
  • +2
9 Comments
 

Author Comment

by:jl66
ID: 37707078
Any gurus: Is it possible?
0
 
LVL 86

Expert Comment

by:jkr
ID: 37707217
What you are describing pretty much sounds like the Singleton Design Pattern. Read more about it at http://sourcemaking.com/design_patterns/singleton and check the code examples at http://sourcemaking.com/design_patterns/singleton/cpp/2
0
 
LVL 29

Expert Comment

by:pepr
ID: 37707711
Actually, any global variable can be shared by whatever part of code.  You should better specify your goal.
0
Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

 

Author Comment

by:jl66
ID: 37707889
Thanks a lot for the tips.

How to define the global variables (structure) that can be shared by two classes (4 files: assume 2 per class: .h and .cpp) before exploring the design pattern? For example,

1) have structure Area
struct Area {
  char Name[10];
  unsigned int x;
  unsigned int y;
};

2) One class
class Expense
{
   // It may assign/update some values into Area and do some thing
};

3) another class
class Pollution
{
  // It will calculate the pollution value with the area.
};

How to make the struct Area as global structure used by these 2 classes?
0
 
LVL 86

Accepted Solution

by:
jkr earned 250 total points
ID: 37707908
Well, the simply make it a global variable, e.g.

#ifndef AREA_H // header guard
#define AREA_H
// area.h
struct Area {
  char Name[10];
  unsigned int x;
  unsigned int y;
};
#ifndef MAIN_CPP
extern Area theGlobalArea;
#endif
#endif

// expense.h
#include "Area.h"
// other declarations

// pollution.h
#include "Area.h"
// other declarations

// main.cpp
#define MAIN_CPP
#include "pollution.h"
#include "expense.h"

Area theGlobalArea; // global instance

int main () {

  // do stuff

  return 0;
}

Open in new window

0
 
LVL 29

Assisted Solution

by:pepr
pepr earned 40 total points
ID: 37708637
... but you should be aware of the fact that global variables can be a source of very nasty errors if the code becomes a bit more complex.  The reason is that the change in one global variable affects all the code that uses the variable.  Sometimes (and especially in GUI applications or in other applications with more logical threads of execution), the modifications of the global variables may happen when you do not expect it.  Sometimes, it may be difficult to demonstrate the problem later (i.e. difficult to debug).  So, there is a big warning when using global variables.  It may be OK if the global variable is filled by few parts of code and then mostly read.

Anyway, it may not fit very well with Object Oriented Design that is basically based on "cooperation of objects".  If the "external" data should only be observed by many places in your code, then the Observer pattern may be the right one (http://en.wikipedia.org/wiki/Observer_pattern).  Basically, you ask the observed object to tell you when something changes.
0
 
LVL 3

Assisted Solution

by:kalpeshchavan
kalpeshchavan earned 100 total points
ID: 37708743
use Singleton pattern

ex
class ABC {

private :
   ABC(){};
public :
int data;
static ABC &getInstance()
{
   static ABC _ins;
   return &_ins;
}

};

// to get Instance of object

ABC &_a=ABC::getInstance();

cout<<_a.data<<endl ;

Open in new window


note : in singleton patter constructor is private and getInstance method is private and it return referance of object ()
0
 
LVL 33

Assisted Solution

by:sarabande
sarabande earned 110 total points
ID: 37709492
the normal way to share data between classes is to have a pointer or reference to the same object or to have pointers or references between the classes themselves:

struct Data
{
    whatevertype wet;
};


class B
{
      // a reference to a Data object
      Data & data;
public:
      // a constructor that takes a Data reference and initializes data member with it
      B(Data & d) : data(d) {  data.wet = ...; }    
};

class A
{
     // contains normal data member
     Data data;
public:
    void memberfunc()
    {
           // create B object   and pass data member
           B b(data);

           // now the data member was shared between class A and B 
    }     
};

Open in new window



struct Data
{
    whatevertype wet;
};


// forward declaration:
class A;

class B
{
      A* parent; 
public:
      // a constructor that takes a reference to A
      B(A* pa) : parent(pa) {  }    

      void memberfunction();
};

class A
{
     // contains normal data member
     Data data;
public:
    Data & getData()
    {
           // create B object   and pass 'this' pointer as parent
           B b(this);
           b.memberfunction();
         
    }     
};

void B::memberfunction()
{
      // get data from parent
      Data & data = parent->getData();
      
      // now share data object with 'parent' of class A
}

Open in new window


Sara
0
 

Author Closing Comment

by:jl66
ID: 37733984
Thanks a lot for everyone's tips. Very helpful.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Unresolved External Symbols 3 109
Math Question 1 105
sorting efficency of sorting algorithm 30 121
c++ using a LPCOLESTR * and adding a string varaible to the Pointer 2 67
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approac…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question