This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Stack allocation skips vtable, optimalisation option?



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@wanadoo.nl
tel;home:053-4323699
tel;cell:06-24732100
version:2.1
end:vcard


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]