LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 1

Calling member functions defined outside the class Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

class Counter {
    int n_ = 0;
public:
    void tick();
    int value() const;
};

void Counter::tick() { n_ += 2; }
int Counter::value() const { return n_; }

int main() {
    Counter a, b;
    a.tick(); a.tick(); b.tick();
    std::cout << a.value() << ' ' << b.value() << '\n';
    return 0;
}
  • A 4 2 Correct
  • B 2 2
  • C 6 6
  • D 4 4
Correct Answer: Option A

Defining the functions outside with Counter:: makes no difference to behaviour. Each object has its own n_.

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