Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the type of a constructor?

I know constructor do not have a return type. Though I wonder, what is the type of a constructor then? Does a constructor have a type?

I tried this

struct A { A() {} };

template <typename A> struct foo;

int main() { foo< decltype(&A::A) > f; }

to get the error (gcc)

prog.cc: In function 'int main()':
prog.cc:5:32: error: taking address of constructor 'constexpr A::A(A&&)'
    5 | int main() { foo< decltype(&A::A) > f; }
      |                                ^
prog.cc:5:35: error: template argument 1 is invalid
    5 | int main() { foo< decltype(&A::A) > f; }
      |                                   ^

...well, ok I cannot take the address. Also this fails:

int main() { foo< decltype(A::A) > f; }

with

prog.cc: In function 'int main()':
prog.cc:5:32: error: decltype cannot resolve address of overloaded function
    5 | int main() { foo< decltype(A::A) > f; }
      |                                ^
[...]

which is probably just a very confusing error message caused by the same reason as above (cannot take adress of constructor) and I dont know what else to try..

What is the type of a constructor?

If it has no type, then what is it? Certainly it is not A (member_function)().

PS: To clarify what is my confusion: cpprefernce states

Constructor is a special non-static member function of a class that is used to initialize objects of its class type.

And my logic goes like this: Member function have a type, constructors are special kinds of member functions, hence they should have a type. I know the reasoning is flawed, but why?

like image 707
463035818_is_not_a_number Avatar asked Dec 08 '22 11:12

463035818_is_not_a_number


2 Answers

I think these quotes from the C++ 17 Standard will be relevant (15.1 Constructors)

1 Constructors do not have names....

and

2 A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name lookup; however an explicit type conversion using the functional notation (8.5.1.3) will cause a constructor to be called to initialize an object. [ Note: For initialization of objects of class type see 15.6. — end note ]

and

10 A return statement in the body of a constructor shall not specify a return value. The address of a constructor shall not be taken.

like image 149
Vlad from Moscow Avatar answered Dec 27 '22 08:12

Vlad from Moscow


Constructors effectively do not have types.

It may be surprising that the standard doesn't say this explicitly, but since they do not have names, do not participate in name lookup, cannot have their address taken and are "functions" with no return type, it's deducible.

like image 43
Lightness Races in Orbit Avatar answered Dec 27 '22 08:12

Lightness Races in Orbit