构造函数不能被继承的原因
Posted Key_Ky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了构造函数不能被继承的原因相关的知识,希望对你有一定的参考价值。
If constructors were inherited in C++, it would cause many undesirable problems, and the main benefit of inheritance of members would not apply to constructors.
Here are some problems if constructors were inherited in C++.
- Subclasses are forced to support all the methods of construction of superclasses. A subclass often implements a more specific specialization of the parent class. But if constructors were inherited, then that means it must be also possible to construct the subclass using any constructor of the superclass, even ones that may be too general to be applicable to this particular subclass. The only way for the subclass to deal with this is to explicitly override the unwanted constructors, and throw an error or something; this is a bad solution because it is not checked at compile time, only detected at runtime. Or, the language needs to add a new construct for the class declaration to "un-inherit" a constructor; which is also messy.
- C++ has multiple inheritance. If a class inherits from multiple classes, would it inherit constructors from both parent classes? If both parent classes have a constructor with the same signature, how would that be resolved?
- A constructor in C++ has an "initializer list" where it provides arguments for the construction of the base class(es) and fields. A base class or field not explicitly specified in the initializer list is default constructed (i.e. constructed with a constructor of no parameters). If such an omitted base class or field type is not default-constructible, the constructor does not compile. However, if constructors were inherited, the user would not get to specify the initializer list for that constructor for the derived class. What if there are fields in that derived class which are not default-constructible? How can this problem be prevented? Disallow all derived classes from having non-default-constructible fields? That would be way too restrictive.
More importantly, the main benefit of inheritance do not apply to constructors:
- The main benefit of inheritance is subtype polymorphism. If you have a pointer or a reference to a base class type, it can point to an object of that type or any derived type. You can access fields and virtual methods using that pointer/reference to base class type, and it will work even if the pointer points to an object of derived class type, without you knowing, or caring, what that type actually is. However, for constructors, this is not relevant, because any place where a constructor is invoked, you explicitly specify the class name to be constructed. There is no situation where you could call a constructor on an object that could possibly be different types; it wouldn‘t make sense.
以上是关于构造函数不能被继承的原因的主要内容,如果未能解决你的问题,请参考以下文章