8

This is my code

#include <iostream>

class A {
public:
    int a = 0;
    A(int i = 0) : a(i) {}
};

void func(A())
{
    std::cout << "Hello" << std::endl;
}

int main()
{
    A(*p)() = NULL;
    func(p);
}

What confused me is that A() in void func(A()) is equal to A(*)() instead of A's constructor. How does this work?

Gabriel Ravier
  • 358
  • 1
  • 6
  • 17

1 Answers1

9

Let’s reason by analogy. If you define a function

void doSomething(A [137]) {

}

then C++ treats it as though you’d actually written

void doSomething(A *) {

}

In other words, there are some types where, if you use them as a parameter to a function, C++ will automatically replace them with a different type, the type you’d get by decaying the type.

In your case, A() is the type of a function that takes in no arguments and returns an A. If you have a C++ function that takes an A() as an argument, C++ will instead have the function take as input an A (*)(), a pointer to a function taking no arguments and returning an A. The reason for this is that you can’t have an object of type A() in C++, though you can have a pointer to an A().

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065