What is the output of the following snippet? #include <iostream> using namespace std; class A { friend class B; private: int field; public: int set(int x) { return field = ++x; } int get() { return ++field; } }; class B { public: void kill(A &a) { a.field = 0; } }; int main() { A a; B b; a.set(1); b.kill(a); cout << a.get(); return 0; } 0 Compilation fails 2 1
Question
What is the output of the following snippet?
#include <iostream> using namespace std;
class A { friend class B; private: int field; public: int set(int x) { return field = ++x; } int get() { return ++field; } };
class B { public: void kill(A &a) { a.field = 0; } };
int main() { A a; B b; a.set(1); b.kill(a); cout << a.get(); return 0; }
0
Compilation fails
2
1
Solution
The output of the given C++ code snippet will be 1.
Here's the step by step explanation:
-
Class A is defined with a private integer field, a public set method that increments the input and assigns it to the field, and a get method that increments the field and returns it. Class B is declared as a friend of Class A, which means it can access A's private and protected members.
-
Class B is defined with a public method kill that takes an object of Class A as a reference and sets its field to 0.
-
In the main function, objects of Class A and Class B are created.
-
The set method of Class A is called with 1 as the argument. This increments 1 to 2 and assigns it to the field.
-
The kill method of Class B is called with the object of Class A as the argument. This sets the field of Class A to 0.
-
The get method of Class A is called, which increments the field from 0 to 1 and prints it.
So, the output will be 1.
Similar Questions
What is the output for the following code?
What does the following code snippet do?
What is the output of the following code in Python?
What is the output for the following code?Note: This question helps in clearing conceptual technical interviews for service-based companies.
What will be the output of the following PHP code?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.