0
0
C++programming~20 mins

Encapsulation best practices in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Encapsulation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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;
}
A10
BCompilation error due to private member access
C0
DRuntime error
Attempts:
2 left
πŸ’‘ Hint
Private members cannot be accessed directly outside the class, but public methods can access them.
🧠 Conceptual
intermediate
1:30remaining
Purpose of encapsulation in C++
Which of the following best describes the main purpose of encapsulation in C++?
ATo make all class members public by default
BTo hide internal data and only expose necessary parts through methods
CTo allow direct access to all class members from anywhere
DTo increase the size of the class objects
Attempts:
2 left
πŸ’‘ Hint
Think about protecting data inside a class.
πŸ”§ Debug
advanced
2: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;
};
AMaking data members public so they can be accessed directly
BUsing private data members with public getter and setter methods
CDeclaring data members as private and initializing them in constructor
DUsing const methods to access data members
Attempts:
2 left
πŸ’‘ Hint
Encapsulation means restricting direct access to data.
πŸ“ Syntax
advanced
2: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++?
Aclass Sample { public: int value; int getValue() { return value; } private: };
Bclass Sample { private int value; public int getValue() { return value; } };
Cclass Sample { private: int value; public: int getValue() { return value; } };
Dclass Sample { private: int value; public: int getValue() { return value } };
Attempts:
2 left
πŸ’‘ Hint
Check for correct use of colons, semicolons, and access specifiers.
πŸš€ Application
expert
2: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?
}
A0
B2
C3
D1
Attempts:
2 left
πŸ’‘ Hint
Remember the meaning of private, protected, and public access.