Reputation: 5947
Non mumber function can be delcared multiple times while member function can only be declared once? Is this right ? My example seems saying yes.
But Why ?
class Base{
public:
int foo(int i);
//int foo(int i=10); //error C2535: 'void Base::foo(int)' : member function already defined or declared
};
//but it seems ok to declare it multiple times
int foo(int i);
int foo(int i=10);
int foo(int i)
{
return i;
}
int main (void)
{
int i = foo();//i is 10
}
Upvotes: 2
Views: 889
Reputation: 361472
From the Standard (2003), §8.3.6/4 says,
For non-template functions, default arguments can be added in later declarations of a function in the same scope.
Example from the Standard itself:
void f(int, int);
void f(int, int = 7);
The second declaration adds default value!
Also see §8.3.6/6.
And an interesting (and somewhat related) topic:
And §9.3/2,
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.
Hope that helps.
Upvotes: 6
Reputation: 17114
You get the same result with this simplified version:
int foo() ;
int foo() ; // OK -- extern functions may be declared more than once
class C {
int foo() ;
int foo() ; // Error -- member function may not be declared more than once
} ;
Perhaps the reason is historical -- lots of C
code used redeclaration of extern
functions, so they had to be allowed.
Upvotes: 1