What is the output of this C++ program that uses getter and setter methods?
#include <iostream> class Box { private: int length; public: void setLength(int l) { length = l; } int getLength() { return length; } }; int main() { Box b; b.setLength(10); std::cout << b.getLength() << std::endl; return 0; }
Check what value is assigned by the setter before calling the getter.
The setter sets the private variable length to 10. The getter returns this value, so the output is 10.
What will this program print if the setter is never called?
#include <iostream> class Box { private: int length = 5; public: void setLength(int l) { length = l; } int getLength() { return length; } }; int main() { Box b; std::cout << b.getLength() << std::endl; return 0; }
Look at the default value of the private variable.
The private variable length is initialized to 5. Since the setter is not called, the getter returns 5.
What error will this code produce when compiled?
#include <iostream> class Box { private: int length; public: void setLength(int l) { length = l; } int getLength() const { return length; } }; int main() { Box b; b.setLength(7); std::cout << b.getLength() << std::endl; return 0; }
Check if const correctness is properly used.
The getter is marked const, which is allowed. The setter is non-const, but it is called on a non-const object. The code compiles and outputs 7.
Which of the following setter method definitions will cause a compilation error?
Consider what const means for member functions.
A setter modifies the object, so it cannot be marked const. Option D tries to modify length inside a const method, causing a compilation error.
Given the following code, what is the final output?
#include <iostream> class Counter { private: int count = 0; public: void setCount(int c) { if (c >= 0) { count = c; } } int getCount() { return count; } }; int main() { Counter c; c.setCount(5); c.setCount(-3); c.setCount(10); std::cout << c.getCount() << std::endl; return 0; }
Notice the condition inside the setter method.
The setter only updates count if the new value is zero or positive. The call with -3 is ignored. The final value set is 10.