天天看点

Note:Behavior of polymorphic methods inside constructors

thinking in java中的一个例子,java和C++表现不是特别一致:

#include <iostream>

using namespace std;

class Base {

public:

Base() {

cout << "Before draw" << endl;

Draw();

cout << "After draw" << endl;

}

virtual void Draw() const {

cout << "Base.Draw()" << endl;

}

};

class Derived : public Base {

private:

int i;

public:

void Draw() const {

cout << "Derived.Draw(), i: " << i << endl;

}

};

void f(const Base& b) {

b.Draw();

}

int main() {

Derived d;

f(d);

return 0;

}

/*

* output

Before draw

Base.Draw()

After draw

Derived.Draw(), i: 10944660

*/

package thinkingInJava.polymorphism;

import static thinkingInJava.util.Print.*;

class Base {

public Base() {

println("Before draw");

Draw();

println("After draw");

}

public void Draw(){

println("Base.Draw()");

}

}

class Derived extends Base {

private int i = 10;

public void Draw() {

println("Derived.Draw(); i: " + i);

}

}

public class Inside210 {

public static void main(String[] args) {

new Derived();

}

}

/*

* output

Before draw

Derived.Draw(); i: 0

After draw

*/