I have seen two styles of defining conversion operator overload in C++,
operator int* (void) const
operator int*() const
Question 1. I think the two styles (whether add void
or not) have the same function, correct?
Question 2. Any preference which is better?
This doesn't just apply to conversion operators but to all functions in C++ that take no parameters. Personally, I prefer to omit void
for consistency.
The practice originates from C. Originally, when C did not have prototypes, an empty pair of braces was used in function declarations and did not provide any information about the parameters that the function expected.
When prototypes were added, empty braces were retained for function declarations to mean 'unspecified parameters' for flexibility and backwards compatibility. To provide an explicit prototype meaning 'takes no parameters', the syntax (void)
was added.
In C++ all function declarations have to have prototypes, so ()
and (void)
have the same meaning.
Quoting from ISO C++ FAQ, Should I use f(void)
or f()
?
C programmers often use
f(void)
when declaring a function that takes no parameters, however in C++ that is considered bad style. In fact, thef(void)
style has been called an "abomination" by Bjarne Stroustrup, the creator of C++, Dennis Ritchie, the co-creator of C, and Doug McIlroy, head of the research department where Unix was born.If you're writing C++ code, you should use
f()
. Thef(void)
style is legal in C++, but only to make it easier to compile C code.
Appeal to authority FTW :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With