Virtual functions in constructors, why do languages differ?

前端 未结 6 1565
攒了一身酷
攒了一身酷 2021-01-04 09:56

In C++ when a virtual function is called from within a constructor it doesn\'t behave like a virtual function.

I think everyone who encountered this behavior for the

6条回答
  •  遥遥无期
    2021-01-04 10:04

    Virtual functions in constructors, why do languages differ?

    Because there's no one good behaviour. I find the C++ behaviour makes more sense (since base class c-tors are called first, it stands to reason that they should call base class virtual functions--after all, the derived class c-tor hasn't run yet, so it may not have set up the right preconditions for the derived class virtual function).

    But sometimes, where I want to use the virtual functions to initialize state (so it doesn't matter that they're being called with the state uninitialized) the C#/Java behaviour is nicer.

提交回复
热议问题