Is this legal in Standard C++ ?

Started by
5 comments, last by GameDev.net 18 years, 10 months ago
simple code below:
void foo() {
}
void foo(int i = 0) {
}

int main()
{
    //foo(); // call of overloaded 'foo()' is ambiguous	
}

The code is successfully compiled on gcc 3.3.3 But when I added "foo();" in main(), gcc gave this error: call of overloaded 'foo()' is ambiguous. Is this overload legal in Standard C++ ?
Advertisement
No. A function with no parameters, and a function with one parameter that has a default value are indistinguishable from each other. You could be calling foo(void) or you could be calling foo(0), it just can't tell.

Take away the = 0 and you'll be in business.

CM
No. When you comment out the function call, gcc will not process those functions, as they are never called. As soon as you add it in, it won't be able to choose one function over the other.

How did you expect it to work?

karg
You might be able to get a way with it by making your default constructor (taking no parameters) as private. This may provide enough information for the compiler to resolve the ambiguity in main(). Note that this doesn't really solve the issue per se, it simply hides it from one side. You can still create an ambiguity in your class code .

e.g.

void foo(){  private:    void foo() {}  public:    void foo(int i = 0) {}    void foo(char c) : foo() {}  // ambiguity here?}
Hello neverland,

Yes both are valid functions.

They will get name mangling by compiler into 2 different name functions.
If you were creating a lib these should be in it.

example:
readable name => expanded compiler name mangling
void foo() => foo_v
void foo(int i=0) => foo_si

Both can be compile into obj files.

The problem you have is when you try to use the function the compiler doesn't know which one to expand out as a function name if no argument given.

Which one should it use?
foo() or foo(0).

It is a bad thing to do to give a compiler such a choice.
I would make the int one not have a default value.

Lord Bart :)
Quote:Original post by Anonymous Poster
You might be able to get a way with it by making your default constructor (taking no parameters) as private. This may provide enough information for the compiler to resolve the ambiguity in main(). Note that this doesn't really solve the issue per se, it simply hides it from one side. You can still create an ambiguity in your class code .

e.g.

*** Source Snippet Removed ***


I'm not sure what you were trying to show with your example, but very little of what you posted even comes close to resembling compileable C++ code.
Quote:Original post by Polymorphic OOP
I'm not sure what you were trying to show with your example, but very little of what you posted even comes close to resembling compileable C++ code.


Yikes! You're right. I don't know where my mind was!

This topic is closed to new replies.

Advertisement