Home >Backend Development >C++ >Why Doesn't My Derived Class Inherit My Base Class's Constructor in C ?

Why Doesn't My Derived Class Inherit My Base Class's Constructor in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 07:35:10558browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn