c++ visitor pattern: Why should every derived visited implement Accept()?

*爱你&永不变心* 提交于 2019-12-05 04:17:21

Inheritance polymorphism (dynamic dispatch) does not apply to function arguments. In other words, overloaded function are selected on the static type of the arguments being passed. If implemented in the base class Color, the v->visit(*this) would always call visit(Color c).

If the only accept you had was...

void Color::accept(Visitor* v)
{
    v->visit(*this);
}

visit would just get called with a base class. In order to call visit with the correct derived class you need each Color to implement it so they can pass a correctly typed this, so the correct visit overload is called.

My understanding is that in base class methods the this pointer is of type base, not of any derived classes, hence it can only access base class methods, and is passed as type Color* this. When passed to the visit method it would try and run visit(Color* color), as polymorphic behavior only applies to methods of the class itself (not other classes).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!