I wonder, why it is not allowed to write:
struct foo {
void bar(); // declaration
void bar(){std::cout << "moo" << std::endl;} // declaration + definition
};
The function is declared twice (I thought this is ok) and defined once. However, my compiler complains about:
decldef.cxx:7:10: error: 'void foo::bar()' cannot be overloaded
Why is it not allowed?
Why does my compiler (g++ 4.7.2) interpret this as overloading?
PS: I know how to write it "the correct way", but I just would like to know, why the above is wrong.
From §9.3
Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared.
In addition, in this case the statements may also fall foul of:
A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.
As the first declaration does not declare the function to be inline
. The second definition implicitly does.
However, that one on reflection seems less convincing.
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