现在的位置: 首页 > 综合 > 正文

What’s the behavior when calling an overwritten virtual method in the constructor method of a base class?

2019年03月11日 ⁄ 综合 ⁄ 共 1476字 ⁄ 字号 评论关闭

What’s the behavior when calling an overwritten virtual method in the constructor method of a base class? This is a frequently asked question in a technical interview. In practice, we should avoid such case. But we need to know the answer. This is a so confusing problem that C++ and Java behave differently.

 

For C++, the method in base class, not derived class, is called.

 

For Java, the method in derived class, not base class, is called. But apparently, the default value of field in derived class is used because it is not initialized at that time. When base class constructor calls virtual methods in derived class, the whole object is a partial object.

 

抱歉!评论已关闭.