M
moleskyca1
I've ran into a problem with inheritance and STL containers. The code
is too much to list, but here is the basic problem:
#include <queue>
using namespace std;
class Base
{
public:
typedef queue<Base *> BaseQ;
void DoBase(BaseQ &) {;} // should work on any queue of Base or a Base
subtype
};
class Derived: public Base
{
public:
typedef queue<Derived *> DerivedQ;
};
// have other derived types from base: Derived1, Derived2, etc...
int main(int argc, _TCHAR* argv[])
{
Derived *dp = new Derived();
Base *bp(dp); // (A) this is legal as expected (upcasting)
Derived:erivedQ dv; dv.push(dp);
bp->loopBase(dv); // (B) compiler says this is illegal, cannot convert
from queue<Derived *> & to queue<Base *> &
return 0;
}
If line (A) is legal, why isn't like (B) legal as well? There are
operations in Base that must apply to containers of any derived of
base. It seems wasteful to have to create a temporary queue<Base *> and
load it with the contents of queue<Derived *> to call loopBase()
(that's what I do now). Is there a better way?
is too much to list, but here is the basic problem:
#include <queue>
using namespace std;
class Base
{
public:
typedef queue<Base *> BaseQ;
void DoBase(BaseQ &) {;} // should work on any queue of Base or a Base
subtype
};
class Derived: public Base
{
public:
typedef queue<Derived *> DerivedQ;
};
// have other derived types from base: Derived1, Derived2, etc...
int main(int argc, _TCHAR* argv[])
{
Derived *dp = new Derived();
Base *bp(dp); // (A) this is legal as expected (upcasting)
Derived:erivedQ dv; dv.push(dp);
bp->loopBase(dv); // (B) compiler says this is illegal, cannot convert
from queue<Derived *> & to queue<Base *> &
return 0;
}
If line (A) is legal, why isn't like (B) legal as well? There are
operations in Base that must apply to containers of any derived of
base. It seems wasteful to have to create a temporary queue<Base *> and
load it with the contents of queue<Derived *> to call loopBase()
(that's what I do now). Is there a better way?