-3

i have a variable map dataa ehich is used in three different class.i can define this variable globally and put all classes defination in one cpp file but i want to make different files for three different class and thus cant define it globally.

now i want to define this variable in one class say A and then want to use this dataa in the rest two class say B and C.

how can i do this.thanks for anyhelp in advance

Mcolorz
  • 145
  • 1
  • 5
  • 20

3 Answers3

0

You can use public get and set methods to access your variable in class A. Or simply create a public variable in class A.

Paul Seleznev
  • 672
  • 1
  • 11
  • 24
  • i have declared that variable as static map dataa; according to the answers i have seen at some places but that isnt helping and i have no idea about this get set method.please help me out with an example – Mcolorz Jul 09 '12 at 14:13
0

alternatively you can try to have this variable map data as part of a new singleton class. The rest of your 3 different classes can access this singleton class using get method

file: singleton.h

#include <iostream>
using namespace std;

class singletonClass
{
  public:
      singletonClass(){};
      ~singletonClass(){};

  //prevent copying and assignment
  singletonClass(singletonClass const &);
  void operator=(singletonClass const &);

  //use this to get instance of this class
  static singletonClass* getInstance()
  {
     if (NULL == m_Singleton)  //if this is the first time, new it!
        m_Singleton = new singletonClass;

     return m_Singleton;
  }

  int getData()
  {
     return data;
  }

  void setData(int input)
  {
      data = input;
  }
  private:
    static singletonClass* m_Singleton;  //ensure a single copy of this pointer
    int data;
 };
 //declare static variable as NULL
singletonClass* singletonClass::m_Singleton = NULL;

File: ClassA.h

class ClassA
{
  public:
      ClassA(){};
      ~ClassA(){};

     int getVarFromSingleton()
     {
          m_Singleton = singletonClass::getInstance();  //get a pointer to the singletonClass
          return data = m_Singleton->getData();  //get data from singleton class and return this value
     }
  private:
     singletonClass* m_Singleton;  //declare a pointer to singletonClass
     int data;
 };

File: main.cpp

int main()
{
singletonClass* DataInstance;
ClassA a;
int data;

DataInstance = singletonClass::getInstance();

DataInstance->setData(5);

data = a.getVarFromSingleton();

cout << "shared data: " << data << endl;

return 0;

}

0

You can use friends

class A
{
friend class B;
friend class C;
private:
int m_privateMember;
};

class B {
};

class C {
};

Now, B and C can access to A's private members.

But this is not the best way. Try to avoid it.

legotron
  • 61
  • 4