views:

27

answers:

3

I have

class CBase
{
.......
};

class CDerived : public CBase
{
......
};

vector<CBase*> mpBase;
vector<CDerived*>::iterator InfoIt;

InfoIt=mpBase.begin();

VC++ 2008 generates error C2679. What's wrong?

A: 

That's not legal. You need to use an iterator that's of the same type as the vector. If the vector really contains pointers to CDerived objects, make it vector<CDerived*>. If it doesn't, you'll need to try downcasting the objects in the vector, which, of course, may not succeed. You may want to look into dynamic_cast in that case.

Scott Wolchok
A: 

Not all CBase*s are CDerived*s. Say there are other classes derived from CBase. Then what does it mean to interpret CDerived2* as a CDerived*? What does it mean to interpret a CBase* as a CDerived*? It is possible to put both of those types in a CBase vector.

stonemetal
A: 

You could always use a simple pointer object; CDerived* foo = (CDerived*)*(mpBase.begin());. But like the others have said, that may not always be possible.

Fredrik Ullner