Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!uakari.primate.wisc.edu!aplcen!uunet!maverick.ksu.ksu.edu!ux1.cso.uiuc.edu!suna2!nelson From: nelson@suna2 (Taed Nelson) Newsgroups: comp.lang.c++ Subject: Efficient compilation of virtual functions Message-ID: <1990Aug22.193347.18486@ux1.cso.uiuc.edu> Date: 22 Aug 90 19:33:47 GMT Sender: usenet@ux1.cso.uiuc.edu (News) Reply-To: nelson@suna2.UUCP (Taed Nelson) Organization: Picasso Group, University of Illinois at Urbana-Champaign Lines: 59 I was wondering how intelligent the C++ compilers (I have the newest releases of G++ an CFront) were with respect to virtual functions. It appears that the answer is "not very." If we have a virtual member function in the base class, and the same member function is redeclared in the subclass, whenever we are using an instance of the subclass, there is _no need_ to consult the virtual function table since we will _always_ call the subclass function. In addition, there are other cases where we do not have to consult the virtual function table. Unfortunately, I could get neither of the compilers to avoid looking at the virtual function table in such a clear-cut case. This is important for a number of reasons (to me especially): 1. Virtual lookup is comparatively expensive. 2. We are unable to inline virtual functions. To examine the behavior of the following code, I used the following lines: g++ -O -finline-functions -S xxx CC -O -S xxx Am I missing something? Shouldn't this be an easy optimization for these compilers to make? Anyone know of a way to get around this limitation? In the following code, subclassPointer->mutate() should DEFINITELY be inlined/non-looked-up and the other two could be since there are no other uses of the ptrs. -------------- int number = 0; // so that no optimizations can be done class base { public: virtual void mutate () { number = 1; }; }; class subclass : public base { public: void mutate () { number = 2; }; }; main () { base *basePointer = new base; subclass *subclassPointer = new subclass; base *indirectPointer = new subclass; basePointer->mutate(); subclassPointer->mutate(); // this should be optimized/inlined indirectPointer->mutate(); } ------------------