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 32,692 of 33,346   
   Edmund Kapusniak to All   
   Casting a pointer-to-member from derived   
   26 Nov 12 16:17:01   
   
   From: birotanker@this.is.invalid   
      
   { Please limit your text to fit within 80 columns, preferably around 70,   
     so that readers don't have to scroll horizontally to read each line.   
     This article has been reformatted manually by the moderator. -mod }   
      
   Hello,   
      
     Is this valid C++?   
      
   #include    
      
   class base   
   {   
   };   
      
   class derived : public base   
   {   
   public:   
       virtual void method() { printf( "x()\n" ); }   
   };   
      
   void (base::*pmethod)() = static_cast< void (base::*)() >( &derived::method );   
      
   int main( int argc, char* argv[] )   
   {   
       derived d;   
       base* b = &d;   
       ( b->*pmethod )();   
       return 0;   
   }   
      
     It appears to work, since b really does point to a derived.  However I   
   am concerned that it might be undefined behaviour, since I do not cast   
   back to a void (derived::*)() before dereferencing to the   
   pointer-to-member.  Obviously if b pointed to a base (or an unrelated   
   subclass of base) then this wouldn't work at all.   
      
     I am hoping that it is legal.  I think that it is useful to be able to   
   dispatch calls to methods identified by their pointer-to-members without   
   having to write a custom dispatch routine for each derived class.   
      
     Any answers appreciated!   
      
     Thanks,   
      
   Edmund   
      
      
   --   
         [ 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