Can someone help explain the following?
Why is it that elements 5 - 9 in Bar::group do not seem to resolve to
elements 0 - 4 of Bar::group when de-referenced?
If I am following this correctly I would assume the following is
happening.
Elements 0 - 4 of Bar::group are created when Bar mainlist is
declared in main.
Elements 5 - 9 of Bar::group are created within the for loop
of main.
Within this loop elements 0 - 4 of mainlist which refer to elements
0 - 4 of Bar::group are set to point at elements 5 - 9 of Bar::group.
Once this assignment is done elements 0 - 4 of mainlist and elements
0 - 4 of Bar::group both point to elements 5 - 9 of Bar::group.
But if I make a change to a member of one ot the elements 0 - 4 of
mainlist the change is reflected in elements 0 - 4 of Bar::group but
not in the corresponding 5 - 9 element of Bar::group?
Thanks for any clarification.
#include <iostream.h>
template <class T> class Foo {
public:
T list[10];
};
class Bar {
public:
Bar() {
static int i = 0;
cout << "Creating " << i ;
group.list[i] = this;
id = i;
i++;
cout << " : " << id << endl;
}
void setID(int i) { id = i; }
int getID() { return id; }
Foo<Bar*>* getList() { return &group; }
private:
static Foo<Bar*> group;
int id;
};
Foo<Bar*> Bar::group;
int main() {
int i;
// Elements 0 - 4 are created in Bar::group
Bar mainlist[5];
// Elements 5 - 9 are created in Bar::group
for(i = 0; i < 5; i++) {
Bar *tmp = new Bar();
// Elements 0 - 4 in Bar::group are set to point at
// Elements 5 - 9 of Bar::group
mainlist[i] = *tmp;
}
// Change id of Element 2 of Bar::group
mainlist[0].getList()->list[2]->setID(9999);
// No Change of id in Element 7 in Bar::group ?
for(i = 0; i < 10; i++)
cout << mainlist[0].getList()->list[i]->getID() << endl;
return 0;
}