From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 11844 invoked by alias); 28 Jul 2005 09:21:09 -0000 Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org Received: (qmail 11590 invoked by uid 22791); 28 Jul 2005 09:20:51 -0000 Received: from smtp06.wanadoo.nl (HELO smtp06.wanadoo.nl) (194.134.35.146) by sourceware.org (qpsmtpd/0.30-dev) with ESMTP; Thu, 28 Jul 2005 09:20:51 +0000 Received: from [10.1.1.5] (dc5146ff27.adsl.wanadoo.nl [81.70.255.39]) by smtp6.wanadoo.nl (Postfix) with ESMTP id 949811D59C for ; Thu, 28 Jul 2005 11:20:49 +0200 (CEST) Message-ID: <42E8A370.4040602@wanadoo.nl> Date: Thu, 28 Jul 2005 09:21:00 -0000 From: Daan Oosterveld User-Agent: Mozilla Thunderbird 1.0 (Windows/20041206) MIME-Version: 1.0 To: gcc-help@gcc.gnu.org Subject: Stack allocation skips vtable, optimalisation option? Content-Type: multipart/mixed; boundary="------------000904000702050406000005" X-SW-Source: 2005-07/txt/msg00311.txt.bz2 This is a multi-part message in MIME format. --------------000904000702050406000005 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-length: 1292 Hi all, I have a problem finding the right switch to eliminate the compiler to jump over the vtable and calling the wrong virtual function. When allocating a class on the stack and copying a subclass over it virtual functions don't behave as expected. As a pointer the code calls the virtual function of the subclass, but when called directly it always calls the function in the base class. The compiler assumes the pointer to the vtable is to Foo, and then assumes to call Foo::foo() in stead of looking in the object and see the vtable is pointing at Bar and calling Bar::foo. The output of this is: $ ./a.out Foo! Bar! It should be in my opinion: $ ./a.out Bar! Bar! The source is listed below. It is compiled without optimalisations (-O0) Thanks Daan Oosterveld ---- source: #include class Foo { protected: char aap[12]; public: Foo() {} Foo(const Foo & foo) { char * d = (char*)this; char * s = (char*)&foo; for(int i = 0; i < sizeof(Foo); i ++) { d[i] = s[i]; } } virtual void foo() { printf("Foo!\n"); } }; class Bar : public Foo { public: virtual void foo() { printf("Bar!\n"); } }; int main() { Foo foo = Bar(); Foo * bar = &foo; foo.foo(); bar->foo(); } --------------000904000702050406000005 Content-Type: text/x-vcard; charset=utf-8; name="d.oosterveld.vcf" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="d.oosterveld.vcf" Content-length: 153 begin:vcard fn:Daan Oosterveld n:Oosterveld;Daan email;internet:d.oosterveld@wanadoo.nl tel;home:053-4323699 tel;cell:06-24732100 version:2.1 end:vcard --------------000904000702050406000005--