Bird
Raised Fist0
C++programming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of encapsulation in C++?
easy
A. To make the program run faster
B. To hide data and protect it from unauthorized access
C. To allow direct access to all class members
D. To increase the size of the program

Solution

  1. Step 1: Understand encapsulation concept

    Encapsulation means hiding the internal details of a class to protect data.
  2. Step 2: Identify the main goal

    The goal is to prevent wrong or unauthorized changes by restricting direct access.
  3. Final Answer:

    To hide data and protect it from unauthorized access -> Option B
  4. Quick Check:

    Encapsulation = Data protection [OK]
Hint: Encapsulation means hiding data safely [OK]
Common Mistakes:
  • Thinking encapsulation speeds up code
  • Believing all data should be public
  • Confusing encapsulation with inheritance
2. Which of the following is the correct way to declare a private data member in a C++ class?
easy
A. private: int age;
B. int age; // private by default
C. protected int age;
D. public int age;

Solution

  1. Step 1: Recall C++ access specifiers

    Private members must be declared after the keyword 'private:' in a class.
  2. Step 2: Check each option

    private: int age; uses 'private:' correctly before 'int age;'. Others are either public, protected, or missing specifier.
  3. Final Answer:

    private: int age; -> Option A
  4. Quick Check:

    Private members use 'private:' label [OK]
Hint: Use 'private:' label before private members [OK]
Common Mistakes:
  • Assuming members are private by default
  • Using 'private' without colon
  • Declaring private members as public
3. What will be the output of this C++ code?
class Box {
private:
    int length;
public:
    void setLength(int len) { length = len; }
    int getLength() { return length; }
};

int main() {
    Box b;
    b.setLength(10);
    std::cout << b.getLength();
    return 0;
}
medium
A. 0
B. Compilation error
C. 10
D. Garbage value

Solution

  1. Step 1: Understand class methods

    The method setLength sets the private member length to 10.
  2. Step 2: Check output statement

    getLength returns length, which was set to 10, so output is 10.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    Setter sets 10, getter returns 10 [OK]
Hint: Setter sets value, getter returns it [OK]
Common Mistakes:
  • Expecting default 0 without setting
  • Thinking private members can't be accessed via methods
  • Confusing compilation error due to private member
4. Identify the error in this C++ class related to encapsulation:
class Person {
public:
    int age;
    void setAge(int a) { age = a; }
    int getAge() { return age; }
};

int main() {
    Person p;
    p.age = -5;
    std::cout << p.getAge();
    return 0;
}
medium
A. Age should be private to prevent invalid values
B. setAge method is missing return type
C. getAge should be private
D. No error, code is correct

Solution

  1. Step 1: Check data member access

    Age is public, so it can be set directly to invalid value -5.
  2. Step 2: Understand encapsulation best practice

    Age should be private and setAge should validate input to prevent invalid values.
  3. Final Answer:

    Age should be private to prevent invalid values -> Option A
  4. Quick Check:

    Private data prevents invalid direct changes [OK]
Hint: Make data private to control changes [OK]
Common Mistakes:
  • Thinking public data is safe
  • Believing getters should be private
  • Ignoring validation in setters
5. You want to protect a class's data member balance so it cannot be set to a negative value. Which is the best encapsulation practice to achieve this?
hard
A. Make balance public and check value outside the class
B. Make balance protected and allow derived classes to set it freely
C. Remove balance and use a global variable instead
D. Make balance private and provide a setter that validates input

Solution

  1. Step 1: Understand data protection need

    To prevent negative values, direct access must be blocked.
  2. Step 2: Use private data with validation

    Making balance private and using a setter method to check values ensures safety.
  3. Final Answer:

    Make balance private and provide a setter that validates input -> Option D
  4. Quick Check:

    Private data + validated setter = safe encapsulation [OK]
Hint: Use private data and validate in setter [OK]
Common Mistakes:
  • Leaving data public for easy access
  • Using protected without validation
  • Using global variables for encapsulation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard