Stack allocation skips vtable, optimalisation option?

Daan Oosterveld d.oosterveld@wanadoo.nl
Thu Jul 28 09:21:00 GMT 2005


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

-------------- next part --------------
A non-text attachment was scrubbed...
Name: d.oosterveld.vcf
Type: text/x-vcard
Size: 153 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20050728/b2514375/attachment.vcf>


More information about the Gcc-help mailing list