Challenge - 5 Problems
Data Hiding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of private member access attempt
What will be the output of this C++ code?
C++
class Box { private: int length; public: Box(int l) : length(l) {} }; int main() { Box b(10); // std::cout << b.length << std::endl; // Uncommenting this line return 0; }
Attempts:
2 left
π‘ Hint
Remember that private members cannot be accessed directly outside the class.
β Incorrect
The member 'length' is private, so accessing it directly outside the class causes a compilation error.
β Predict Output
intermediate2:00remaining
Output when accessing private member via public method
What is the output of this C++ program?
C++
#include <iostream> class Box { private: int length; public: Box(int l) : length(l) {} int getLength() { return length; } }; int main() { Box b(15); std::cout << b.getLength() << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Check how the private member is accessed.
β Incorrect
The private member 'length' is accessed through the public method getLength(), so it prints 15.
π§ Conceptual
advanced1:30remaining
Why use private members in a class?
Which of the following is the main reason to declare class members as private in C++?
Attempts:
2 left
π‘ Hint
Think about what data hiding means.
β Incorrect
Private members hide internal details and protect data from being accessed or modified directly from outside the class.
β Predict Output
advanced2:00remaining
Output of friend function accessing private member
What will be the output of this C++ code?
C++
#include <iostream> class Box { private: int length; public: Box(int l) : length(l) {} friend int getLength(Box& b); }; int getLength(Box& b) { return b.length; } int main() { Box b(20); std::cout << getLength(b) << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Friend functions can access private members.
β Incorrect
The friend function getLength can access the private member length and returns 20.
β Predict Output
expert2:30remaining
Value of private member after inheritance and access
What is the output of this C++ program?
C++
#include <iostream> class Base { private: int secret = 42; public: int getSecret() { return secret; } }; class Derived : public Base { public: int getSecretFromDerived() { // return secret; // Uncommenting this line return getSecret(); } }; int main() { Derived d; std::cout << d.getSecretFromDerived() << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Private members are not accessible directly in derived classes.
β Incorrect
The Derived class cannot access 'secret' directly because it is private in Base, but it can call Base's public method getSecret().