c++functiontypesconstructorlanguage-lawyer

Does a constructor have a "type" since it is a special member function?


I recently learnt that constructors do not have names. I am also aware that a function has a type called a function type. For example,

void func(int)
{
}

In the above snippet, func has the function type void (int).

Now, since constructors are special member functions, do they also have a type like the one shown above? For example say we have:

struct Name
{ 
    Name(int)
    {
    }
};

Does the constructor shown above also have a function type just like ordinary functions or ordinary member functions? If yes, then how can we find that type? Is it permitted to use decltype on constructors to find their type, like one would do for ordinary functions?


Solution

  • Does a constructor have a "type"

    This is CWG2476 whose status is DRWP(meaning accepted in C++26 working draft) which also makes constructors have a type. Note as published c++23 did not allow constructors to have a type:

    C++23

    Here T in T D is not allowed to be empty meaning a constructor doesn't have a type in C++23 as published.

    From dcl.fct:

    1. In a declaration T D where D has the form
     D1 ( parameter-declaration-clause ) cv-qualifier-seqopt
       ref-qualifieropt noexcept-specifieropt attribute-specifier-seqopt
    
    1. In a declaration T D where D has the form
     D1 ( parameter-declaration-clause ) cv-qualifier-seqopt
       ref-qualifieropt noexcept-specifieropt attribute-specifier-seqopt trailing-return-type  
    

    The optional attribute-specifier-seq appertains to the function type.

    1. A type of either form is a function type.

    Note here T was not allowed to be empty before CWG2476 meaning a constructor function doesn't have a type in C++23.


    CWG2476

    In the working draft of C++26, T can be empty, meaning now constructors do have a type.

    [Accepted as a DR at the March, 2024 meeting.]

    1. Change in 9.3.4.6 [dcl.fct] paragraph 1 as follows:

    In a declaration T D where T may be empty and D has the form :

    D1 ( parameter-declaration-clause ) cv-qualifier-seqopt
     ref-qualifieropt noexcept-specifieropt attribute-specifier-seqopt trailing-return-typeopt
    

    A type of either form is a function type.

    Note the emphasis on T may be empty added in the above CWG which means the constructor Name::Name(int) does have a type.