ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
void f(bool)        { cout << "bool "; }
void f(std::string) { cout << "string "; }
void g(int)         { cout << "int "; }
void g(std::string) { cout << "string "; }
int main() {
    f("hi");
    f(std::string("hi"));
    g('a');
}
  1. A. string string string
  2. B. string string int
  3. C. bool string int
  4. D. bool string string

Correct answer: C. bool string int

"hi" is a const char array that decays to a pointer, and pointer to bool is a standard conversion. Reaching std::string needs a user-defined conversion (its constructor), and any standard conversion sequence beats a user-defined one, so f("hi") prints bool - a classic surprise. An actual std::string matches exactly. 'a' promotes to int, again a standard conversion.

More OOP with C++ and Java questions

Exams that ask this topic