Question

I have a question about functions that take no arguments in C++, and possibly also C.

I am writing a simple program, which has a class. That class has a certain static method. This is what the header file could look like:

class SampleClass {
public:
    SampleClass();
    ~SampleClass();
    static void CertainMethod();
}

The CertainMethod() takes no arguments, is static, and should print out "SAMPLETEXT". My question is, why do we still need the brackets when calling it? Here are two pieces of main():

int main(int argc, const char** argv) {
SampleClass::CertainMethod();
system("pause");
return 0;
}

and

int main(int argc, const char** argv) {
SampleClass::CertainMethod;
system("pause");
return 0;
}

The purpose of both snippets is to print out "SAMPLETEXT", which is done by CertainMethod. Both of them compile successfully, but only the first one works. There is a warning when compiling the second snippet: warning C4551: function call missing argument list.

Why do we still have to put in the brackets in order for it to work, even though the code compiles successfully without them, and the function does not take in any arguments?

Was it helpful?

Solution

SampleClass::CertainMethod is the name of a function.

The name of a function implicitly decays into a pointer to the function in many use contexts.

Suppose you had:

void foo( void(*)() )

which is a function foo that takes a pointer to a function. Then

foo( SampleClass::CertainMethod )

would pass a pointer to SampleClass::CertainMethod to foo to do with it what it will.

SampleClass::CertainMethod cannot invoke the function, because then you could not talk about a pointer to it!

In your case, you are naming the function, then discarding it. You are allowed to do this in C++ -- you can have a statement like this:

int a = 3, b = 5;
a+b;

that a+b adds a to b, then discards the result. Expressions are legal statements.

This is also legal:

a;

which is a simple expression that evaluates to 3, but does nothing with the value.

So your line was an expression that evaluated a pointer or reference to SampleClass::CertainMethod. Warning-worthy, but still legal C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top