LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 14

Default access in struct and class Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Pixel { int r = 0, g = 0, b = 0; };

class Brush {
    int size_ = 3;
public:
    int size() const { return size_; }
    void grow() { if (size_ < 10) ++size_; }
};

int main() {
    Pixel p;
    p.g = 255;
    Brush b;
    for (int i = 0; i < 9; ++i) b.grow();
    std::cout << p.r << ',' << p.g << ' ' << b.size() << '\n';
    return 0;
}
  • A 0,255 10 Correct
  • B 0,255 12
  • C 255,255 10
  • D Compilation error
Correct Answer: Option A

A struct's members are public by default, which suits a plain Pixel. Brush keeps its size private and caps it at 10 however often grow() is called.

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