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');
}- A. string string string
- B. string string int
- C. bool string int
- 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
- What is printed on a typical platform (16-bit short, 32-bit int)? cpp int i = -1; unsigned int u = 1; short s = -1; unsigned short us = 1…
- Which lines fail to compile? cpp struct A { explicit A(int) { } }; struct B { B(int) { } }; void takeA(A) { } void takeB(B) { } int main()…
- What is printed? cpp struct N { int v = 0; N& operator++() { cout << "pre "; ++v; return this; } N operator++(int) { cout << "post "; N t…
- What is printed? java String s = "a,b,,c,,"; System.out.print(s.split(",").length);
- What is printed? java System.out.print(",x,".split(",").length + " " + "".split(",").length);
- What is printed? java String a = "Aa", b = "BB"; Set<String> set = new HashSet<>(); set.add(a); set.add(b); System.out.print((a.hashCode()…