Re: Why can't pass vector of "Derived" to function that takes vector of "Base"?
by nickf3 <nickf3@[EMAIL PROTECTED]
>
Apr 28, 2008 at 11:22 PM
On Apr 28, 6:05 pm, Rob <someidunknown1...@[EMAIL PROTECTED]
> wrote:
> I have these cl***** (elided methods):
>
> class Base
> {
> public:
> Base(string name) {...}
>
> };
>
> class Derived : public Base
> {
> public:
> Derived(String name) : Base( name ) {...}
>
> };
>
> And neither of these work:
>
> /*** ATTEMPT ONE **/
> void create(std::vector<Base>& arr)
> {
> ...
> }
>
> int main()
> {
> std::vector<Derived> arr;
> create( arr );
> }
>
> /*** ATTEMPT TWO **/
> void create(std::vector<Base*>& arr)
> {
> ...
> }
>
> int main()
> {
> std::vector<Derived*> arr;
> create( arr );
> }
vector<Base> and vector<Derived> are unrelated types.
They are not connected by inheritance like the types they
contain, so they don't behave polymorphically. Example:
class B {};
class D: public B {};
struct A { class B b; };
struct C { class D d; };
C c;
A& a( c ); // ERROR
You can insert Derived into vector<Base>, and Derived*
into vector<Base*> though (with slicing in the first case)
--
Nikolai
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]