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 7 of 9 Topic 9558 of 9775
Post > Topic >>

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

by Brendan Miller <catphive@[EMAIL PROTECTED] > Apr 29, 2008 at 10:37 AM

On Mon, 28 Apr 2008 16:05:53 CST, Rob wrote:
>       /*** ATTEMPT TWO **/
>       void create(std::vector<Base*>& arr)
>       {
>             ...
>       }
> 
>       int main()
>       {
>            std::vector<Derived*> arr;
>            create( arr );
>       }

It isn't type safe. Imagine if the langauge did allow you to do this. What
if create was implemented like:

void create(std::vector<Base*>& arr)
{
   arr.push_back(new Base());
}

Then since arr was passed by reference, the vector<Derived*> arr in main
would contain an object of type Base, when it's type says it only contains
objects of derived! Main could access an object of type base, and call a
Derived specific member function on it, and then you have undefined
behavior.

That would break type safty, and since the whole point of templates is
type
safty, it would destroy the purpose of templates.

If you want to pass in a vector of Derived objects to a function that
takes
Base objects, make a vector<Base*> and just populate it with Derived.
Derived objects are Base, but not the other way around.

-- 
      [ 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 Tue Jul 8 23:20:36 CDT 2008.