shared member between class instances

M

markww

Hi,

I want all instance of a class type to share one variable, I forgot how
to do that:

class CMyClass {

public:
static int m_nSharedRes;
};

Now can all instances of CMyClass share that one variable, and see the
changes reflected in each instance? Like:

CMyClass a;
CMyClass b;

a.m_nSharedRes = 44;

// Now b can see it as 44 too.
cout << b.m_nSharedRes << endl; // should print 44;

Thanks!
 
S

Steve Pope

markww said:
Hi,

I want all instance of a class type to share one variable, I forgot how
to do that:

class CMyClass {

public:
static int m_nSharedRes;
};

Now can all instances of CMyClass share that one variable, and see the
changes reflected in each instance? Like:

CMyClass a;
CMyClass b;

a.m_nSharedRes = 44;

// Now b can see it as 44 too.
cout << b.m_nSharedRes << endl; // should print 44;

Thanks!

If you define it somewhere with

int CMyClass::m_nSharedRes;

it should work as you intended.

Steve
 
M

markww

Steve said:
If you define it somewhere with

int CMyClass::m_nSharedRes;

it should work as you intended.

Steve

Hi Steve,

So I just define it like:

class CMyClass {

public:
int CMyClass::m_nSharedRes;
};

??

Thanks
 
G

Greg

markww said:
Hi Steve,

So I just define it like:

class CMyClass {

public:
int CMyClass::m_nSharedRes;
};

??

No, m_nSharedRes must be declared static in order for each CMyClass
object to share the same variable.

Greg
 
S

Steve Pope

markww said:
Steve Pope wrote:
So I just define it like:

class CMyClass {

public:
int CMyClass::m_nSharedRes;
};

??

The definition:

int CMyClass::m_nSharedRes;

needs to be outside of the declaration of the class. You need
to do this in addtion to the code in your first post. Remember
that the a class declaration by itself allocates no storage.

Steve
 
M

markww

Steve said:
The definition:

int CMyClass::m_nSharedRes;

needs to be outside of the declaration of the class. You need
to do this in addtion to the code in your first post. Remember
that the a class declaration by itself allocates no storage.

Steve

Ah yeah now I remember. Thanks guys,

Mark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top