-2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
awwd
  • 19
  • 5
  • 3
    If you don't understand it, why do you use it? – The Dreams Wind Nov 23 '22 at 15:54
  • 1
    "_I created ..."_ _"...This looks unecessary"_ then get rid of it. Also you don't appear to have asked a question. – Richard Critten Nov 23 '22 at 15:55
  • 3
    This brings constructors of `std::runtime_error` into `invalid_assignment` scope. So without this you have only default constructor of `invalid_assignment`. – Marek R Nov 23 '22 at 15:56
  • [Documentation page for what you're asking about](https://en.cppreference.com/w/cpp/language/using_declaration). Sometimes the right thing to do is experiment. Remove it and see how the program breaks. You can't always count on this approach because of undefined behaviour, but in this case if it's really important you'll get a compiler error. You can trust the compiler error, UB... not so much. – user4581301 Nov 23 '22 at 16:03

1 Answers1

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335