Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding void func(A())

Tags:

c++

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?

like image 722
meisheng shen Avatar asked Nov 28 '19 13:11

meisheng shen


People also ask

How does void function work?

When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."

What is void function example?

Void functions are mostly used in two classes of functions. The first is a function that prints information for the user to read. For example (for our purposes), the printf function is treated as a void function.

What is void * function?

Void functions, also called nonvalue-returning functions, are used just like value-returning functions except void return types do not return a value when the function is executed. The void function accomplishes its task and then returns control to the caller. The void function call is a stand-alone statement.

What does a void function do in C?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.


1 Answers

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().

like image 177
templatetypedef Avatar answered Oct 03 '22 13:10

templatetypedef