Claire Huang
Claire Huang

Reputation: 981

Modify an object without using it as parameter

I have a global object "X" and a class "A". I need a function F in A which have the ability to modify the content of X.

For some reason, X cannot be a data member of A (but A can contain some member Y as reference of X), and also, F cannot have any parameter, so I cannot pass X as an parameter into F. (Here A is an dialog and F is a slot without any parameter, such as accept() )

How can I modify X within F if I cannot pass X into it? Is there any way to let A know that "X" is the object it need to modify?? I try to add something such as SetItem to specify X in A, but failed.

Upvotes: 1

Views: 267

Answers (3)

dash-tom-bang
dash-tom-bang

Reputation: 17843

If you don't want F to reference X globally, then you could 'set' it on the object before calling the "worker" method. E.g.

class A
{
public:
   A() : member_x(NULL) { }
   void SetX(X* an_x) { member_x = an_x; }
   void F(); { member_x->Manipulate(); }

private:
   X* member_x;
};

X global_x;
A global_a;

void DoStuff()
{
   global_a.SetX(&global_x);
   global_a.F();
}

Upvotes: 4

Michael Chinen
Michael Chinen

Reputation: 18697

Since X is a global object you should be able to access it from A::F().
For example:

In B.h:

class B
{
public: 
  B(){x=1};
  virtual ~B(){}
  ChangeSomething(){x=2;}
private:
  int x;
};

In main.cpp

#include "A.h"
#include "B.h"

B X;

int main( int argc, const char* argv[] )
{
  A instanceOfA;
  instanceOfA.ModifyGlobalObject();
}

in A.h

#include "B.h"
extern B X;
class A
{
public:
  ModifyGlobalObject(){X.ChangeSomething();}
};

Of course these classes and global variables can be in different files if you include the headers correctly.

Upvotes: 1

sickgemini
sickgemini

Reputation: 551

If X is global, you can set it it within the A::F function.

extern X

class A
{
   void F()
   {
        // set the global variable X
        X = someValue;
   }
};

Upvotes: 0

Related Questions