Home >Backend Development >C++ >Why Don't Derived Classes Inherit Constructors in C and How Can We Fix It?

Why Don't Derived Classes Inherit Constructors in C and How Can We Fix It?

DDD
DDDOriginal
2025-01-05 08:52:40715browse

Why Don't Derived Classes Inherit Constructors in C   and How Can We Fix It?

Inheriting Constructors: A Tale of Inheritance

In the provided code snippet, we observe an error when attempting to initialize an object of class B with B *b = new B(5);, despite the presence of a constructor in the base class A. This raises the question of why inherited constructors are not accessible in this case.

The key to understanding this issue lies in the intricate rules of constructor inheritance in C . In the absence of explicit constructor inheritance, derived classes do not automatically inherit constructors from their base classes. This was the case in the C 03 standard. To achieve constructor inheritance, the derived class must explicitly use the using keyword, as seen in the following corrected code:

class A {
    public:
        explicit A(int x) {}
};

class B: public A {
     using A::A;
};

With the addition of using A::A;, class B now inherits the constructor from class A, resolving the error. It's important to note that this inheritance applies to all constructors in the base class, and the derived class cannot selectively inherit only certain constructors.

If your compiler supports the C 11 standard, you can utilize the using keyword for constructor inheritance. However, in the C 03 standard, constructors were not inherited by default, and had to be manually implemented in the derived class by calling the base constructor.

For templated base classes, the using keyword can also be employed to inherit constructors as demonstrated in this example:

template<class T>
class my_vector : public vector<T> {
    public:
    using vector<T>::vector; ///Takes all vector's constructors
    /* */
};

The above is the detailed content of Why Don't Derived Classes Inherit Constructors in C and How Can We Fix It?. 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