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

How Can I Inherit Constructors in C ?

Linda Hamilton
Release: 2024-12-25 15:30:10
Original
606 people have browsed it

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;
}
Copy after login

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;
};
Copy after login

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
    /* */
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template