Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with SetState() GetState()?

Status
Not open for further replies.

golyg

Programmer
Jul 22, 2002
319
US
I am trying to set a variable in one .cpp file with a SetState() function and from another .cpp I want to retrieve it with a GetState() function.
I was curious about the rules: should they be public or private.
One other thing, if there are more than one variable(instance) should I do the SetState() and GetState() calls within the init function.
thanks,
 
The SetState and GetState methods need to be 'public' as they will be called by instances of the class - if they were 'private' they would only be callable within the actual class code itself.

The data behind the SetState and GetState methods can either be different for each instance of the class or you can set/return the same data for all instances by defining the data as 'static' within the class.

----------------------------------------------

class Example1
{
private:
int i;

public:
Example1 ();
void SetData (int x) {i = x;}
int GetData () {return i;}
};

Example1 c1;
Example1 c2;

c1.SetData (1);
c2.SetData (2);

int i = c1.GetData (); // returns 1
i = c2.GetData (); // returns 2

-------------------------------------------------
class Example2
{
private:
static int i;

public:
Example2 ();
void SetData (int x) {i = x;}
int GetData () {return i;}
};

int Example2::i = 0;

Example2 c1;
Example2 c2;

c1.SetData (1);
c2.SetData (2);

int i = c1.GetData (); // returns 2
i = c2.GetData (); // returns 2
--------------------------------------------------------

There might be a few typos in the above, but hopefully you get the idea.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top