Home >Backend Development >C++ >How Can I Inherit Constructors in C ?

How Can I Inherit Constructors in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 15:30:10610browse

How Can I Inherit Constructors in C  ?

Inheriting Constructors

The code snippet you provided:

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

class B: public A
{
};

int main(void)
{
    B *b = new B(5);
    delete b;
}

produces errors when compiled with GCC because it lacks a matching constructor for B(int). While you might expect B to inherit A's constructor, this is not the case by default in C .

In C 11 and later, a new feature called constructor inheritance using using has been introduced. By adding using A::A; within class B, you can explicitly inherit all of A's constructors.

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

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

However, constructor inheritance is an all-or-nothing concept. You cannot selectively inherit only certain constructors. If you attempt to do so, you will need to manually define the desired constructors and explicitly call the base constructor from each of them.

In C 03 and earlier, constructor inheritance was not supported. Constructors had to be inherited manually by individually calling the base constructor in each derived class constructor.

For templated base classes, you can use template syntax to inherit all constructors. For 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 How Can I Inherit Constructors 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