Reputation: 18429
Why doesn't this compile?
class Test
{
void foo();
void foo()
{ }
};
But these will compile:
void bar();
void bar()
{ }
// In same header/file
class Test
{
void foo();
};
void Test::foo()
{ }
The compiler would say that given method cannot be overloaded. The method Test::foo
is not being overloaded - it is the same function with exact same signature.
Upvotes: 0
Views: 171
Reputation: 1
Why doesn't this compile?
class Test {
void foo();
void foo() { }; // wrong
};
Because, as StoryTeller and others answered, you are declaring and defining the same member function void Test::foo(void)
twice (and the inside-class definition of foo
is implicitly inline
).
If you want to define a member function in your header file after the class, you'll better declare it explicitly as inline
like this:
class Test {
inline void foo();
};
and later define that member function (e.g. below in the same header file):
void Test::foo() {
// body of Test::foo
}
BTW, if you declare a member function with outside definition like above, and that member function is not inline
but is defined in some header file which is included in several translation units, that function would be multiply defined and the linker would complain.
Upvotes: 1
Reputation: 2735
void foo();
and
void foo() {}
are two ways of declaring functions in a class definition. The first only declares the function and the second declares the function and also implements it. Therefore the compiler assumes that you are going to re-declare the same function and is not a correct overload as the function signature is the same in both.
Upvotes: 0
Reputation: 320631
It is just the way it is in C++. Redeclaring a class member is not allowed (unless you consider an out-of-class definition as another declaration). Redeclaring a namespace member is OK as long as you obey ODR.
Upvotes: 1
Reputation: 170153
It's explicitly prohibited by the C++ standard. Right there at [class.mfct/1]
A member function may be defined in its class definition, in which case it is an inline member function, or it may be defined outside of its class definition if it has already been declared but not defined in its class definition. A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition. 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 ([temp.spec]) appearing outside of the class definition, a member function shall not be redeclared.
Upvotes: 5