Search code examples
c++virtual

virtual function calls and casting


i receive an unexpected output from some code like this:

struct A
{
    virtual void foo(){ std::cout << "A::foo()\n";
};

struct B : A
{
    virtual void foo(){ std::cout << "B::foo()\n";
};

int main()
{
    A* a = new B;

    a->foo();
    (static_cast< A* >( a ))->foo( );

    delete a;
}

the output is:

B::foo()
B::foo()

this is a very simplified example. my question is:

  • why does the second call to foo( ) print "B::foo()"?

i expected it to result in "A::foo()"

auto ptr = static_cast< A* >( a );  
// ide :: ptr is of type A*
// a call to ptr->foo() still reults in "B::foo()";

thank you :)


Solution

  • Virtual functions work through the object itself. Inside the A or B structures, there is some information (typically called a vtable) which contains the pointers to the virtual function(s), in this case, foo.

    This is kind of the point, that you WANT to call the function that belongs to some object that is of a different type than the actual pointer (typically a "base"-class, where you have multiple derived classes).

    To force the call to A::foo, you would call (the rather awkward syntax of):

    a->A::foo()
    

    But generally, I'd say "you're doing it wrong" if you do that sort of thing - that isn't how you should be using virtual functions.