Virtual member call in a constructor

后端 未结 18 2133
[愿得一人]
[愿得一人] 2020-11-22 01:27

I\'m getting a warning from ReSharper about a call to a virtual member from my objects constructor.

Why would this be something not to do?

18条回答
  •  孤城傲影
    2020-11-22 02:09

    Your constructor may (later, in an extension of your software) be called from the constructor of a subclass that overrides the virtual method. Now not the subclass's implementation of the function, but the implementation of the base class will be called. So it doesn't really make sense to call a virtual function here.

    However, if your design satisfies the Liskov Substitution principle, no harm will be done. Probably that's why it's tolerated - a warning, not an error.

提交回复
热议问题