Challenge - 5 Problems
Encapsulation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of private member access in C++
What is the output of this C++ code snippet?
C++
class Box { private: int length; public: Box(int l) : length(l) {} int getLength() { return length; } }; int main() { Box b(10); // std::cout << b.length << std::endl; // Uncommenting this line causes error std::cout << b.getLength() << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Private members cannot be accessed directly outside the class, but public methods can access them.
β Incorrect
The private member 'length' cannot be accessed directly outside the class, but the public method getLength() returns its value. So the output is 10.
π§ Conceptual
intermediate1:30remaining
Purpose of encapsulation in C++
Which of the following best describes the main purpose of encapsulation in C++?
Attempts:
2 left
π‘ Hint
Think about protecting data inside a class.
β Incorrect
Encapsulation hides internal data and exposes only what is necessary through public methods, protecting data integrity.
π§ Debug
advanced2:00remaining
Identify the encapsulation violation
Which option shows a violation of encapsulation best practices in C++?
C++
class Person { public: std::string name; int age; };
Attempts:
2 left
π‘ Hint
Encapsulation means restricting direct access to data.
β Incorrect
Making data members public allows external code to modify them directly, breaking encapsulation.
π Syntax
advanced2:00remaining
Correct syntax for private member with getter
Which option shows the correct syntax for declaring a private member and a public getter method in C++?
Attempts:
2 left
π‘ Hint
Check for correct use of colons, semicolons, and access specifiers.
β Incorrect
Option C uses correct syntax: access specifiers with colons, semicolons after class, and method body with braces.
π Application
expert2:30remaining
Number of accessible members from outside the class
Given this class, how many members can be accessed directly from outside the class?
C++
class Data { private: int secret; protected: int semi_secret; public: int open; Data() : secret(1), semi_secret(2), open(3) {} }; int main() { Data d; // Which members can be accessed directly here? }
Attempts:
2 left
π‘ Hint
Remember the meaning of private, protected, and public access.
β Incorrect
Only public members can be accessed directly outside the class. Here, only 'open' is public.