usage of using keyword in struct C++

127 views Asked by At

I created an exception like this in my header_file run.h

struct invalid_assignment : std::runtime_error {
   using std::runtime_error::runtime_error; 
}; 

I dont understand the using std::runtime_error::runtime_error; part. This looks unecessary.

1

There are 1 answers

0
Vlad from Moscow On

From the C++ 17 Standard (10.3.3 The using declaration)

3 In a using-declaration used as a member-declaration, each using-declarator’s nested-name-specifier shall name a base class of the class being defined. If a using-declarator names a constructor, its nested-name-specifier shall name a direct base class of the class being defined.

and

16 For the purpose of overload resolution, the functions that are introduced by a using-declaration into a derived class are treated as though they were members of the derived class. In particular, the implicit this parameter shall be treated as if it were a pointer to the derived class rather than to the base class. This has no effect on the type of the function, and in all other respects the function remains a member of the base class. Likewise, constructors that are introduced by a using-declaration are treated as though they were constructors of the derived class when looking up the constructors of the derived class (6.4.3.1) or forming a set of overload candidates (16.3.1.3, 16.3.1.4, 16.3.1.7). If such a constructor is selected to perform the initialization of an object of class type, all subobjects other than the base class from which the constructor originated are implicitly initialized (15.6.3).

Thus this using declaration

using std::runtime_error::runtime_error;

introduces constructors of the class std::runtime_error in the class invalid_assignment as if they are constructors of the class invalid_assignment.