LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Predict the Output · Question 18

Default arguments acting as a default constructor Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

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

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

class Pizza {
    std::string size_;
    int toppings_;
public:
    Pizza(std::string size = "medium", int toppings = 2) : size_(std::move(size)), toppings_(toppings) {}
    void show() const { std::cout << size_ << '/' << toppings_ << ' '; }
};

int main() {
    Pizza a, b("large"), c("small", 0);
    Pizza menu[2];
    a.show(); b.show(); c.show(); menu[1].show();
    std::cout << '\n';
    return 0;
}
  • A medium/2 large/2 small/0 medium/2 Correct
  • B medium/2 large/0 small/0 medium/2
  • C /0 large/2 small/0 /0
  • D Compilation error
Correct Answer: Option A

Because every parameter has a default, the constructor can be called with no arguments and serves as the default constructor – also for array elements.

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