Home >Backend Development >C++ >Why Doesn't My Derived Class Inherit My Base Class's Constructor in C ?
Inheriting Constructors: An Enigma
When constructors are not inherited as expected, it can be puzzling. Consider the following code snippet:
class A<br>{</p> <pre class="brush:php;toolbar:false">public: explicit A(int x) {}
};
class B: public A
{
};
int main(void)
{
B *b = new B(5); delete b;
}
This code generates compilation errors:
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&)
Unexpectedly, class B does not inherit the constructor from class A.
Unveiling the Solution
In C 03, constructors were not inherited automatically. To inherit a constructor, it needed to be manually called from the derived class constructor. However, with C 11's constructor inheritance, this limitation was alleviated.
Harnessing Constructor Inheritance
With C 11, using the using keyword allows inheritance of all constructors from the base class. To do this, simply add the following line to the derived class:
using A::A; // Inherits all constructors from class A
By using this technique, all constructors from the base class are inherited into the derived class.
Exception Handling
It's important to note that if a derived class manually defines a constructor, it will not inherit any constructors from the base class. In such cases, all constructors must be manually defined and explicitly call the base class constructor as needed.
Templated Base Classes
For templated base classes, a similar approach is employed. To inherit all constructors from a templated base class into a derived class, use the following syntax:
using vector<T>::vector; /// Takes all vector's constructors
This approach ensures that all constructors from the base class are inherited into the derived class.
The above is the detailed content of Why Doesn't My Derived Class Inherit My Base Class's Constructor in C ?. For more information, please follow other related articles on the PHP Chinese website!