Reputation: 471
I am trying to make an array of distinct objects. However, I notice that whenever I change one object from the array, all elements receive that change. Obviously, I want only the object at that index to receive the change. Here is my code:
//Creates the array pointer
cacheStats **directMappedTable1024Bytes = new cacheStats *[31];
//Initializes the array with cacheStats objects
for (int i=0; i<31; i++)
{
table[i] = new cacheStats();
}
//Test: Changing element of one object in the array
directMappedTable1024Bytes[5]->setTag(55);
cout << directMappedTable1024Bytes[22]->checkTag(); //should output 0
cacheStats code:
#include "cacheStats.h"
int tag;
int valid;
using namespace std;
cacheStats :: cacheStats (int t, int v)
{
tag = t;
valid = v;
}
cacheStats :: ~cacheStats()
{
}
void cacheStats :: setTag (int cacheTag)
{
tag = cacheTag;
}
void cacheStats:: setValidBit (int validBit)
{
valid = validBit;
}
int cacheStats :: checkValid()
{
return valid;
}
int cacheStats :: checkTag()
{
return tag;
}
Results The cout outputs 55, when it should have outputted 0. If I change the preceding line to setTag(32) for example, it will output 32.
Any ideas? Thanks a lot.
Upvotes: 2
Views: 85
Reputation: 500267
The problem is that tag
and valid
are global variables, and as such are shared by all instances of the class. You need to turn them into instance variables (i.e. non-static
data members of the class).
Upvotes: 5