Search code examples
c++oopcastingvirtualbase-class

Does casting actually work when done inside a function call in C++?


My Code:

#include <iostream>

using namespace std;

class A
{
public:
    virtual void print(void) { cout << "I am base class" << endl; }
};

class B : public A
{
public:
    void print(void) { cout << "I am class B" << endl; }
};

void mainprint(A *a)
{
    (*a).print();
}

int main()
{
    A a;
    B b;

    B *bp;
    A *ap;

    ap = &b;

    a.print();
    b.print();
    (*ap).print();

    bp = new B();

    mainprint((A *)bp);

    delete bp;

    return 0;
}

Output:

I am base class
I am class B
I am class B
I am class B

I have casted the pointer(bp) to class A inside the function call, but it still calls the derived class print!!!

Can someone shed some light on this for me.


Solution

  • I have casted the pointer(bp) to class A inside the function call, but it still calls the base class print!!!

    I assume you mean "calls the derived class print", since that's what happened.

    That's the whole point of virtual functions; the final override associated with the actual type of the object (i.e. the "dynamic type") is chosen, whatever the type of the reference or pointer used to call the function (i.e. the "static type"). So B::print is chosen, because bp still points to an instance of B.

    If you want to force a call to A::print, you could do:

    pb->A::print()
    

    or, if you don't want polymorphic behaviour at all, remove the virtual specification.