Maybe you can try this way:
1) build another Index class:
class Index {
static int index = 0;
int my_index;
Index(): my_index( index++ ) {};
int val() { return my_index; };
// ...
}
2) wrap Index objects in your derived classes:
class B: public A {
Index indObj;
int getIndex() {...}; // return indObj.val();
B() //....
}
class C: public A {
Index indObj;
int getIndex() {...}; // return indObj.val();
C() //....
}
3) for each object "B b()", or "C c()" ... associated index by
b.getIndex(), ...
Just a quick idea, didn't try it - supposedly to have lots of glitches,
;) you may work it out. My quick thought is about two guidelines:
1. never try and prevent manually constructing Index objects, so it is
better hidden and wrapped as private in another namespace, while
accessible by B, C, ....
2. depending on the context of your application, you may let index
monotonically gorw, or not.
Another idea is to use smart-pointer, reference pointer counting
pattern, which may need a bit more detailed work-out. Anyway, these're
just some quick brainstorming.
Gary
-: peace
jalina wrote:
Hello,
I want to have classes that all have a unique identifier. It is easy for
a single class:
class A {
static int index;
int my_index;
A(): my_index(index++) { }
};
But if you have something like:
class B: public A {
B() //....
}
class C: public A {
C() //....
}
the "index" is shared among A, B and C's. How can I do to have different
index for each distinct class without having to redefine each time a new
index ?
Thank you from Jalina