Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ Moderated > Re: Why can't p...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 3 of 9 Topic 9558 of 9831
Post > Topic >>

Re: Why can't pass vector of "Derived" to function that takes vector of "Base"?

by Lance Diduck <lancediduck@[EMAIL PROTECTED] > Apr 28, 2008 at 08:35 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:
> snip....

std::vector<Derived*>  and std::vector<Base*> are completely different
types, and unrelated. YOu may as well have said std::vector<Foo*>and
std::vector<Bar*> .
Something similar does work in Java (and that is a recent innovation
in itself -- for the longest time all collections in Java only held
Object and you had to cast things about to get it to work...), but not
C++.
The answer in C++ is to make create a template function, i.e.
template<class T>void create(T&v, int mytype){
   if(mytype==0)v.push_back(new Derived);
   else v.push_back(new Derived2);//something else  derived from Base

}
Lance


-- 
      [ See http://www.gotw.ca/resources/clcm.htm
for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
 




 9 Posts in Topic:
Why can't pass vector of "Derived" to function that takes vector
Rob <someidunknown1234  2008-04-28 16:05:53 
Re: Why can't pass vector of "Derived" to function that takes ve
Chris Uzdavinis <cuzda  2008-04-28 20:36:06 
Re: Why can't pass vector of "Derived" to function that takes ve
Lance Diduck <lancedid  2008-04-28 20:35:36 
Re: Why can't pass vector of "Derived" to function that takes ve
"Hakusa@[EMAIL PROTE  2008-04-28 23:22:39 
Re: Why can't pass vector of "Derived" to function that takes ve
nickf3 <nickf3@[EMAIL   2008-04-28 23:22:53 
Re: Why can't pass vector of "Derived" to function that takes ve
David Pol <david@[EMAI  2008-04-29 10:38:26 
Re: Why can't pass vector of "Derived" to function that takes ve
Brendan Miller <catphi  2008-04-29 10:37:22 
Re: Why can't pass vector of "Derived" to function that takes ve
Anand Hariharan <mailt  2008-04-29 10:44:31 
Re: Why can't pass vector of "Derived" to function that takes ve
Rob <someidunknown1234  2008-04-29 11:13:21 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Fri Jul 25 21:54:07 CDT 2008.