C++ calling completely wrong (virtual) method of an object

后端 未结 4 2101
鱼传尺愫
鱼传尺愫 2021-02-19 03:43

I have some C++ code (written by someone else) which appears to be calling the wrong function. Here\'s the situation:

UTF8InputStreamFromBuffer* cstream = foo();         


        
4条回答
  •  庸人自扰
    2021-02-19 04:18

    I would try removing the C-cast first.

    • It is completely unnecessary, casts from a Derived to a Base is natural in the language
    • It may, actually, cause a bug (though it's not supposed to)

    It looks like a compiler bug... it would certainly not be the first either in VS.

    I unfortunately don't have VS 2008 at hand, in gcc the casts occur correctly:

    struct Base1
    {
      virtual void foo() {}
    };
    
    struct Base2
    {
      virtual void bar() {}
    };
    
    struct Derived: Base1, Base2
    {
    };
    
    int main(int argc, char* argv[])
    {
      Derived d;
      Base1* b1 = (Base1*) &d;
      Base2* b2 = (Base2*) &d;
    
      std::cout << "Derived: " << &d << ", Base1: " << b1
                                     << ", Base2: " << b2 << "\n";
    
      return 0;
    }
    
    
    > Derived: 0x7ffff1377e00, Base1: 0x7ffff1377e00, Base2: 0x7ffff1377e08
    

提交回复
热议问题