Stack allocation skips vtable, optimalisation option?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




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 <stdio.h>

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();
}

begin:vcard
fn:Daan Oosterveld
n:Oosterveld;Daan
email;internet:d.oosterveld@xxxxxxxxxx
tel;home:053-4323699
tel;cell:06-24732100
version:2.1
end:vcard


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux