Complete the code to declare a private member variable in a class.
class Box { private: int [1]; };
The private member variable length is declared inside the class to hide it from outside access.
Complete the code to provide a public method to access the private variable.
class Box { private: int length; public: int [1]() { return length; } };
The method getLength is a public getter that allows controlled access to the private variable length.
Fix the error in the code to prevent direct access to the private variable.
int main() {
Box box;
// box.length = 10; // Error: cannot access private member
box.[1](10);
return 0;
}Using the public setter method setLength allows setting the private variable length safely.
Fill both blanks to complete the setter method for the private variable.
class Box { private: int length; public: void [1](int [2]) { length = [2]; } };
The setter method setLength takes a parameter value to assign to the private variable length.
Fill all three blanks to create a class demonstrating encapsulation with private variable and public getter and setter.
class Box { private: int [1]; public: void [2](int [3]) { length = [3]; } int getLength() { return length; } };
This class uses encapsulation by keeping length private and providing public methods setLength and getLength to access it safely.