What is the output of the following snippet? #include <iostream> using namespace std; class C1 { friend class C2; protected: int y; public: int z; private: int x; public: C1() { x = y = z = 11; } }; class C2 { public: C1 a; C2 () { a.x = 22; }; void foo() { cout << a.x << a.y << a.z; } }; int main() { C2 c; c.foo(); return 0; } 111122 Compilation fails 112211 221111
Question
What is the output of the following snippet?
#include <iostream> using namespace std; class C1 { friend class C2; protected: int y; public: int z; private: int x; public: C1() { x = y = z = 11; } };
class C2 { public: C1 a; C2 () { a.x = 22; }; void foo() { cout << a.x << a.y << a.z; } }; int main() { C2 c; c.foo(); return 0; }
111122
Compilation fails
112211
221111
Solution
The output of the code snippet will be "221111".
Here's the step by step explanation:
-
The class C1 has three integer variables x, y, and z. The variable x is private, y is protected, and z is public. The constructor of C1 initializes all these variables to 11.
-
The class C2 is a friend class of C1, which means it can access the private and protected members of C1. C2 has an object 'a' of class C1 and a constructor that sets the value of 'a's private member 'x' to 22.
-
The function 'foo' in class C2 prints the values of x, y, and z of the object 'a'.
-
In the main function, an object 'c' of class C2 is created. The constructor of C2 is called, which sets the value of 'a's 'x' to 22. Then, the function 'foo' is called on 'c', which prints the values of 'a's x, y, and z.
-
Therefore, the output will be "221111".
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.