Which member is a good candidate for mutable?
mutable members may change inside const functions; using it for real state would make const meaningless.
Encapsulation · Exercise 1 of 4
Twenty multiple-choice questions on encapsulation in C++: data hiding, access rules, invariants, getters and setters, leaking internals, const-correctness, immutability, private inheritance and pimpl. Pick an option to check your answer instantly.
Which member is a good candidate for mutable?
mutable members may change inside const functions; using it for real state would make const meaningless.
What is an important advantage of immutable objects?
Modifications create new objects, so existing ones stay valid forever.
A class has a const int id_; member. What happens to its copy assignment operator?
Objects can still be copy-constructed but not assigned – a trade-off to consider when using const members for immutability.
Why do many guidelines prefer private data with protected member functions over protected data members?
Protected functions let derived classes change state only through checked operations.
What relationship does class Stack : private std::vector<int> express?
Outside code cannot treat a Stack as a vector or call insert on it; using-declarations can re-expose chosen members. A private member is usually simpler.
What is the main purpose of the pimpl idiom?
Private members are part of the class definition users include; pimpl moves them behind an opaque pointer.
A class holds std::unique_ptr<Impl> where Impl is only forward-declared in the header. Why must the destructor be defined in the .cpp file?
An implicitly generated (inline) destructor in the header would try to delete an incomplete type and fail to compile.
Which pairing is correct?
They complement each other: an abstract interface (abstraction) implemented by classes with private data (encapsulation).
When is it reasonable to use a struct with all-public data members?
If any combination of member values is valid, there is nothing to protect.
Which return type gives callers read-only, no-copy access to a private std::vector<double>?
A span of const elements is a view: iteration and reading are allowed, modification is not. const std::vector<double>& also works.
Timed online tests with instant scores and explanations.