C++ Error: No Match for Call
Asked Answered
M

5

6

I'm trying to compile the following code in C++

string initialDecision () 
{
 char decisionReviewUpdate;

 cout << "Welcome. Type R to review, then press enter." << endl;
 cin >> decisionReviewUpdate;

 // Processing code
}

int main()
{
    string initialDecision;
    initialDecision=initialDecision();

    //ERROR OCCURS HERE

 // More processing code
 return 0;
}

Right where it says "Error occurs here", I get the following error while compiling: "Error: No Match for Call to '(std::string) ()'. How can I resolve this?

Menorah answered 10/10, 2009 at 18:11 Comment(0)
F
22

Don't give your string and your function the same name, and the error will go away.

The compiler has "forgotten" that there is a function with that name, when you declare a local variable with the same name.

Faythe answered 10/10, 2009 at 18:13 Comment(0)
M
6

The local variable shadows the name of the global function. It is best to rename the local variable, but there is also the scope operator which lets you specifically access the global name:

initialDecision = ::initialDecision();
Mhd answered 10/10, 2009 at 19:4 Comment(0)
U
5

This is called "name hiding" in C++. In this particular example, you are declaring a local variable, which has the same name as a function in namespace scope. After the point of declaration of that variable the function becomes hidden, and every time you mention the 'initialDecision' name the compiler will rightfully assume that you are referring to the variable. Since you can't apply the function call operator '()' to a variable of type 'string', the compiler issues the error message.

In many cases in order to refer to hidden names you can use the scope resolution operator '::'. See UncleBens response, for example.

Ultramicroscope answered 10/10, 2009 at 19:13 Comment(0)
H
1

Try renaming the variable to not match the name of the function.

Hexahedron answered 10/10, 2009 at 18:13 Comment(0)
B
1

The problem is you are repeating the name initialDecision as both a variable and a function. This confuses the compiler greatly. Try renaming the variable to something else; it will then work.

Biagi answered 10/10, 2009 at 18:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.