Home >Backend Development >C++ >Why Do Inherited Constructors in C Require Explicit Definition Before C 11?
Inheriting Constructors: Understanding the Error and Inheritance Rules
When attempting to inherit a constructor from a base class without explicitly redefining it in the derived class, as illustrated in the provided code snippet, why does it result in a compilation error?
In C , prior to C 11, constructors were not inherited by derived classes. To execute the constructor of the base class, it had to be explicitly called within the derived class's constructor. This is why the following error message is displayed in the given code:
main.cpp:13: error: no matching function for call to ‘B::B(int)’ main.cpp:8: note: candidates are: B::B() main.cpp:8: note: B::B(const B&)
To inherit constructors in C 11 and later, the using keyword is introduced. This keyword can be used to inherit all constructors of the base class collectively.
class A { public: explicit A(int x) {} }; class B: public A { using A::A; // Inherits all constructors of A };
This approach allows you to inherit all constructors of the base class in one line of code. However, it's important to note that selective inheritance of certain constructors is not possible using this method. To achieve selective inheritance, you must manually write individual constructors in the derived class, calling the base class constructor as needed.
The above is the detailed content of Why Do Inherited Constructors in C Require Explicit Definition Before C 11?. For more information, please follow other related articles on the PHP Chinese website!