Jason Drain Jason Drain - 1 year ago 60
C++ Question

Calling a function returning a String within the main method

I am new to C++ and am writing a simple program to test out working with strings. I have defined a separate function that returns a string and want to call it within the main method. The same code works within the main method but I need to define it as a separate function.

My code is below:

7 #include <cstdlib>
8 #include <iostream>
9 #include <string>
11 using namespace std;
13 // function declaration
14 string hi();
16 int main(int argc, char** argv) {
17 // call method
18 string hi;
19 hi = hi();
20 cout << hi << endl;
21 }
23 string hi() {
24 //simple string function
25 return "Hello World";
26 }

And below is the error returned to the console when I try to compile with g++:

test.cpp: In function β€˜int main(int, char**)’:
test.cpp:19:13: error: no match for call to β€˜(std::__cxx11::string {aka std::__cxx11::basic_string<char>}) ()’
hi = hi();

Answer Source

Problem in the Code

You named the variable name and the function name, both hi, so the compiler gets confused about which one you mean.

Solution 1

As @Cheersandhth said, do this:

hi = ::hi();

to get the global hi in its global namespace, which is the function.

Live Example

Solution 2

Otherwise, if you want to change the variable name, you could either change the function name, or the variable, to a different value, and then it would work. Here is an example:

int main(int argc, char** argv)
    string l_hi;
    l_hi = hi();
    cout << l_hi;

Or the alternative:

int main(int argc, char** argv)
    string hi;
    hi = hello();
    cout << hi;
string hello() 
    return "Hello, World!";

Both of these solutions would work, the one you want to use would be a matter of preference. Also, use this answer as advice to not do name shadowing, which could either lead the compiler into picking one of the two names, (provided they fit the right context), or an error may be thrown.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download