Question

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 
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

It certainity works - but I think it is bad practice.

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