Encapsulation helps in protecting data inside a class. Which of the following best explains why encapsulation is important?
Think about how hiding details can protect data from mistakes.
Encapsulation hides the internal state of an object and requires all interaction to be performed through an object's methods. This protects data from unintended interference and misuse.
What will be the output of the following C++ code that uses encapsulation?
#include <iostream> class Box { private: int length; public: void setLength(int len) { if (len > 0) length = len; else length = 0; } int getLength() { return length; } }; int main() { Box box; box.setLength(-5); std::cout << box.getLength(); return 0; }
Look at how setLength handles negative values.
The setLength method sets length to 0 if the input is negative, so the output is 0.
Which option shows a violation of encapsulation principles in C++?
#include <iostream> class Person { public: int age; }; int main() { Person p; p.age = 25; std::cout << p.age; return 0; }
Think about which practice exposes internal data directly.
Making data members public allows direct access and modification, breaking encapsulation.
Choose the C++ code snippet that correctly uses encapsulation to protect the member variable.
Look for private data with public methods to access it.
Option C correctly declares speed private and provides public getter and setter methods, following encapsulation.
Which of the following best explains how encapsulation helps in maintaining large C++ programs?
Think about how hiding details can reduce the impact of changes.
Encapsulation hides internal details, so changes inside a class do not affect other parts of the program, making maintenance easier.