0
0
C++programming~10 mins

Why encapsulation is required in C++ - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a private member variable in a class.

C++
class Box {
private:
    int [1];
};
Drag options to blanks, or click blank then click option'
Aclass
Bpublic
Clength
Dvoid
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using access specifiers like 'public' as variable names.
2fill in blank
medium

Complete the code to provide a public method to access the private variable.

C++
class Box {
private:
    int length;
public:
    int [1]() {
        return length;
    }
};
Drag options to blanks, or click blank then click option'
AgetLength
BsetLength
Clength
DBox
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the variable name itself as the method name without 'get' prefix.
3fill in blank
hard

Fix the error in the code to prevent direct access to the private variable.

C++
int main() {
    Box box;
    // box.length = 10; // Error: cannot access private member
    box.[1](10);
    return 0;
}
Drag options to blanks, or click blank then click option'
ABox
Blength
CgetLength
DsetLength
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Trying to access the private variable directly.
4fill in blank
hard

Fill both blanks to complete the setter method for the private variable.

C++
class Box {
private:
    int length;
public:
    void [1](int [2]) {
        length = [2];
    }
};
Drag options to blanks, or click blank then click option'
AsetLength
Bvalue
Clength
DgetLength
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the private variable name as the parameter name without distinction.
5fill in blank
hard

Fill all three blanks to create a class demonstrating encapsulation with private variable and public getter and setter.

C++
class Box {
private:
    int [1];
public:
    void [2](int [3]) {
        length = [3];
    }
    int getLength() {
        return length;
    }
};
Drag options to blanks, or click blank then click option'
Alength
BsetLength
Cvalue
DgetLength
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Mixing up method names or parameter names.