Question on static attributes in inherited classes

C

C. J. Clegg

If I have...

class ParentClass
{
static int aStaticVar;
};

class ChildClass : public ParentClass
{
static int aStaticVar;
};

.... should the two instances of aStaticVar be the same variable, i.e.
occupy the same memory address?

I understand that in all objectss of ChildClass, aStaticVar will be
the same memory address, and likewise in all objects of ParentClass,
but as between an object of ParentClass and an object of ChildClass, I
would have thought that aStaticVer would be unique.

It doesn't appear to be working that way in g++ version 2.95.
 
S

Sunil Varma

C. J. Clegg said:
If I have...

class ParentClass
{
static int aStaticVar;
};

class ChildClass : public ParentClass
{
static int aStaticVar;
};

... should the two instances of aStaticVar be the same variable, i.e.
occupy the same memory address?

I understand that in all objectss of ChildClass, aStaticVar will be
the same memory address, and likewise in all objects of ParentClass,
but as between an object of ParentClass and an object of ChildClass, I
would have thought that aStaticVer would be unique.

It doesn't appear to be working that way in g++ version 2.95.

A static variable in a class is a global variable with the scope of
that of the class.
So, you are declaring two global variables with different scopes.
They cannot be unique.

Regards
Sunil Varma
 
M

mlimber

C. J. Clegg said:
If I have...

class ParentClass
{
static int aStaticVar;
};

class ChildClass : public ParentClass
{
static int aStaticVar;
};

... should the two instances of aStaticVar be the same variable, i.e.
occupy the same memory address?

No. For one thing, ParentClass::aStaticVar is not visible in ChildClass
since it's private.
I understand that in all objectss of ChildClass, aStaticVar will be
the same memory address, and likewise in all objects of ParentClass,
but as between an object of ParentClass and an object of ChildClass, I
would have thought that aStaticVer would be unique.

They can each only see one of the aStaticVars, but there will be one
and only one ParentClass::aStaticVar among all instances of ParentClass
and ChildClass AND one and only one ChildClass::aStaticVar among all
instances of ChildClass.
It doesn't appear to be working that way in g++ version 2.95.

You might want to ask in a GNU newsgroup.

Cheers! --M
 
C

C. J. Clegg

DISREGARD ... bone-headed move on my part :-(

(now to go see if I can figure out how to cancel a post...)
 

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,780
Messages
2,569,611
Members
45,271
Latest member
BuyAtenaLabsCBD

Latest Threads

Top