For an overloaded function, calling specialized version for parent and child instances

前端 未结 5 931
独厮守ぢ
独厮守ぢ 2021-01-18 12:07

I asked a question earlier but it turns out my problem was not properly modeled by my example. So here is my actual problem:

  1. I have class A, and c
5条回答
  •  隐瞒了意图╮
    2021-01-18 12:43

    Since overloading is resolved at compile time, you need to supply the compiler with enough information to decide on the proper overload of bar to call. Since you wish to make that decision dynamically based on the run-time type of the object, virtual functions would be of great help:

    struct A {
        virtual void bar() { bar(*this); }
    };
    
    struct B : public A {
        virtual void bar() { bar(*this); }
    };
    

    It may seem like the bodies are identical, so B::bar could be eliminated, but this is not true: although the bodies look exactly the same, they call different bars due to the static resolution of overloads in C++:

    • Inside A::bar the type of *this is A&, so the first overload is called.
    • Inside B::bar the type of *this is B&, so the second overload is called.

    Modify the calling code to call the member bar will complete the change:

    std::list l;
    l.push_back(new B());
    l.push_back(new B());
    for (std::list::iterator it = l.begin(); it != l.end(); ++it)
        (*it)->bar();
    

提交回复
热议问题