Don't understand syntax error about "operator()"

In this exercise, I tried making a string variable “Guess” assigned the output from the function Guess().

string Guess = Guess();

I get this cryptic syntax error:

std::string Guess

call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type

The problem is easily resolved by changing the name of either the variable or the function so they don’t exactly match. This is obviously some kind of naming conflict.

I would like to understand this better, because I know this wouldn’t cause problems in Java code.

  1. Can anyone help me decipher the error message, or explain what operator() is?
  2. Why is this a problem? I would have thought variables and functions occupy different namespaces.
  3. Is there a simple syntax trick in C++ that would allow me to use the same named variable and function, kind of like Java’s “this.” syntax?

Here’s a more complete sampling of the code.

string Guess()
{
	// STUFF
	return Guess;
}

int main()
{
	string Guess = Guess();
	return 0;
}

Thanks for any help!

Basically:

Because you can overload the () operator for a class e.g.

#include <iostream>

struct Foo 
{
    void operator() (int i) { std::cout << i; }
};

int main()
{
    Foo foo;
    foo(5); //prints 5
    return 0;
}

I’m understanding a difference in syntax that causes this problem in C++.

In C++, the burden is on the author of a class to make variables and functions distinct. When the class is called, there may not be a difference in syntax when calling a variable or function.

// C++
// variable
&FBullCowGame::Guess

// method
&FBullCowGame::Guess

In Java, the burden is on the programmer who uses the class to have different syntax depending on whether they’re referencing a variable or method.

// Java
// variable
FBullCowGame.Guess

// method, must use parenthesis
FBullCowGame.Guess()

Not entirely sure what you’re getting at because

Is just an address to a data member. You would still use them like

FBullCowGame BCGame;
BCGame.GetGuess();
BCGame.Guess;

Thanks for clarifying, I understand the example now. I haven’t gotten to pointers yet in the course.

Now I realize what the example on stackoverflow means. You can use a pointer to reference either a method or a variable using the same syntax, but they point to a different memory address. To make this unambiguous, the method and variable in a class must be uniquely named.

A few people in the stackoverflow thread say “This is just how C++ works”, but I think a better justification here is “C++ has memory pointers, Java does not.”

Privacy & Terms