In .NET can a class have virtual constructor?

前端 未结 7 1769
别跟我提以往
别跟我提以往 2020-12-15 04:35

Can a class have virtual constructor??

If yes, why it is required?

7条回答
  •  粉色の甜心
    2020-12-15 05:23

    No, how would it work? All constructors in the hierarchy have to be called when you derive child classes from base classes. Making a constructor virtual would imply otherwise.

    Something that may be described as having virtual constructor like behaviour, is when you use the factory pattern. Imagine this scenario:

    class AnimalFactory
    {
        virtual Animal CreateAnimal( return new Animal("Cow"); );
    }
    

    The default behaviour of this factory is to create cows. But if we create a derived class:

    class DogFactory : AnimnalFactory
    {
        override Animal CreateAnimal( return new Animal("Dog"); );
    }
    

    We are now creating dogs. Of course this is not a true virtual constructor (which is impossible), this is virtual construction.

提交回复
热议问题