home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 31,697 of 33,346   
   Dave Harris to Lorenzo Caminiti   
   Re: Covariant virtual function result ty   
   26 Nov 11 13:22:38   
   
   8807a3ed   
   From: brangdon@cix.co.uk   
      
   lorcaminiti@gmail.com (Lorenzo Caminiti) wrote (abridged):   
   > When invoking a covariant virtual function, the derived function   
   > body is executed but the result type of the base function   
   > is returned. Is there any way to get C++ to return the result   
   > type of the derived function instead?   
      
   Only with a run-time test. For example:   
      
       if (y *py = dynamic_cast(px))   
           pry = py->f();   
      
   or:   
       pry = dynamic_cast(px->f());   
      
   There are architectural patterns that replace the dynamic_cast with   
   virtual functions (eg double-dispatching, visitor), but if the compiler   
   doesn't know the run-time type then you need some kind of type-discovery.   
      
      
   Often better is to keep track of the dynamic type statically. That may   
   also involve re-thinking the architecture. For example, using a vector   
   instead of or in addition to a vector. Perhaps whatever you were   
   going to do with the ry you can get y to do for you (and y knows its own   
   type).   
      
   -- Dave Harris, Nottingham, UK.   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca