LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Predict the Output · Question 12

Overloads on int& and const int& Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

What is the output of the following C++ program?

main.cpp
#include <iostream>

void f(int&)       { std::cout << "ref "; }
void f(const int&) { std::cout << "cref "; }

int main() {
    int a = 1;
    const int b = 2;
    f(a);
    f(b);
    f(3);
    f(a + 1);
    std::cout << '\n';
    return 0;
}
  • A ref cref cref cref Correct
  • B ref ref cref cref
  • C ref cref ref cref
  • D cref cref cref cref
Correct Answer: Option A

Only a modifiable variable binds to int&. A const variable, a literal and the temporary a + 1 can only bind to const int&.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links