Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using-declaration for base class constructors

At first sight, using imports a specific function (such as using std::cout to the scope). But this using imports all the base class constructors to the derived class.

template< typename T >
class Vec : public std::vector< T >
{
public:
    using std::vector<T>::vector;  // ???

    //...
};

What's actually behind the scenes of this `using` declaration?
like image 369
artm Avatar asked Aug 03 '26 17:08

artm


1 Answers

As it's public inherited, supposedly all the base class constructors should have been available already (ie why need using)?

No, constructors of the base class are not inherited by default. A detailed explanation can be found in the following discussions:


What's actually behind the scene of this using declaration?

From cppreference.com, using does

  1. Using-declarations can be used to introduce namespace members into other namespaces and block scopes, or to introduce base class members into derived class definitions.
  2. [...] (c++20 specific...)

Also while inheritance:

If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.

like image 139
JeJo Avatar answered Aug 05 '26 08:08

JeJo