您的位置:首页 > 其它

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

2011-05-27 16:26 267 查看
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.

//C++ code
#include <iostream>
using namespace std;

class Glyph{
public:
Glyph() {
cout << "before draw" << endl;
draw(); cout << "end draw" << endl;
}

virtual void draw(){
cout << "Glyph.draw()" << endl;
}
};

class RoundGlyph:public Glyph{
public:
int radius;
RoundGlyph(){ cout << "RoundGlyph.RoundGlyph()" << endl; radius = 1; }
virtual void draw(){ cout << "RoundGlyph.draw()"<<radius << endl; }
};

int main(){
new RoundGlyph();
}

//C++ result
before draw
Glyph.draw()
end draw
RoundGlyph.RoundGlyph()

//Java code
class Glyph {
Glyph(){
System.out.println("Glyph.Glyph() before draw");
draw();
System.out.println("Glyph.Glyph() after draw");
}
void draw(){
System.out.println("Glyph.draw()");
}
}

class RoundGlyph extends Glyph{
private int radus=1;

RoundGlyph (){
System.out.println("RoundGlyph()");
}

void draw(){
System.out.println("RoundGlyph.draw() radus="+radus);
}
}

public class Poly {
public static void main(String[] args){
new RoundGlyph();
}
}

//Java result
Glyph.Glyph() before draw
RoundGlyph.draw() radus=0
Glyph.Glyph() after draw
RoundGlyph()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐