LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Predict the Output · Question 8

Implicit conversion through a converting constructor Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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

main.cpp
#include <iostream>
#include <string>

struct Label {
    std::string text;
    Label(const char* t) : text(t) { std::cout << "[conv]"; }
};

void print(const Label& l) { std::cout << l.text << ' '; }

int main() {
    print("hello");
    print(Label("world"));
    Label x = "!";
    std::cout << x.text << '\n';
    return 0;
}
  • A [conv]hello [conv]world [conv]! Correct
  • B hello world !
  • C [conv]hello world !
  • D Compilation error
Correct Answer: Option A

The non-explicit constructor converts a string literal into a temporary Label each time – implicitly for print("hello") and Label x = "!", explicitly for Label("world").

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