Re: vector of Repository*
* forums_mp@hotmail.com:
Consider:
# include<iostream>
# include<vector>
class CBase {
Consider omitting the "C" prefix for class names. E.g., instead of "CLaw", use
"Law", and instead of "CLick", just "Lick", and instead of "CLamp", just "Lamp".
Then you can talk and think about a "Law" and a "Lick" and a "Lamp" instead of a
"CLaw" and a "CLick" and a "CLamp" (not to mention "Lit" and "Luster").
public :
virtual ~CBase() {}
};
class CDerived1 : public CBase {
public :
};
class CDerived2 : public CBase {
public :
};
// etc.
//later
class Worker {
CDerived1 cd1 ;
unsigned int CDerived1Counter ;
bool CDerived1Flag ;
unsigned int CDerived1ID ;
CDerived2 cd2 ;
unsigned int CDerived2Counter ;
bool CDerived2Flag ;
unsigned CDerived2ID ;
/// etc
public :
};
For this consider templates.
template< class T >
struct Blah
{
T obj;
bool flag;
int id;
};
class Worker
{
Blah<Derived1> d1;
Blah<Derived2> d2;
...
};
The worker class has a ID, a Flag and a counter for each derived
type. An approach that in my view is just silly. So I decided to
create a repository.
struct Repository {
CBase *ptr;
unsigned int Counter ;
bool Flag ;
unsigned int ID ;
Repository ( CBase *ptr_, int BaseClassID )
: ptr ( ptr_ )
, Counter ( 0 )
, Flag ( false )
, ID ( BaseClassID )
{}
};
typedef std::vector < Repository* > REPOSITORY_VEC ;
class RevisedWorker {
static REPOSITORY_VEC rep_vec ;
First, making that "static" means all instances share the same "rep_vec".
That's inconsistent with the earlier original "Worker".
Second, it's generally regarded as best practice to reserve all uppercase names
for macros (except for some few idiomatic usages such as for template params).
public :
RevisedWorker ()
{
rep_vec.push_back ( new Repository ( new CDerived2, 0x400 ) ) ;
rep_vec.push_back ( new Repository ( new CDerived1, 0x300 ) ) ;
// would be nice if i could do.. or perhaps use a map
//rep_vec.add ( new Repository ( new CDerived2, 0x4000 ) )
// .add ( new Repository ( new CDerived1, 0x300 ) ) );
}
};
REPOSITORY_VEC RevisedWorker::rep_vec;
int main() {
RevisedWorker rw;
std::cin.get();
}
At issue: 'new' Repository 'new' CDerivedXX looks unsightey but I'm
not of a reasonable workaround. Ideas? Thanks in advance.
See above, but also keep in mind that you could just make that a vector of
"Repository", not "Repository*".
Cheers & hth.,
- Alf