Recall & Review
beginner
What is a getter method in C++?
A getter method is a function that returns the value of a private class member variable. It allows controlled read access to the variable.Click to reveal answer
beginner
What is a setter method in C++?
A setter method is a function that sets or updates the value of a private class member variable. It allows controlled write access to the variable.Click to reveal answer
intermediate
Why do we use getter and setter methods instead of making variables public?
Getter and setter methods protect the data by controlling how variables are accessed or changed. This helps keep data safe and allows validation before changing values.
Click to reveal answer
beginner
Show a simple example of a getter and setter for a private int variable named 'age'.
class Person {
private:
int age;
public:
int getAge() const { return age; }
void setAge(int a) { if(a >= 0) age = a; }
};Click to reveal answer
intermediate
What happens if you try to set a negative age using the setter in the example?
The setter checks if the age is negative. If it is, it does not change the value, so the age stays valid (non-negative).
Click to reveal answer
What is the main purpose of a getter method?
✗ Incorrect
A getter method allows reading the value of a private variable safely.
Which keyword usually describes variables accessed by getters and setters?
✗ Incorrect
Variables are usually private to protect them and accessed via getters and setters.
What can a setter method do before changing a variable?
✗ Incorrect
Setters often check if the new value is valid before updating the variable.
Which of these is a correct setter signature for an int variable 'score'?
✗ Incorrect
Setters usually return void and take the new value as a parameter.
If a class has a private variable, how can code outside the class access it safely?
✗ Incorrect
Getters and setters provide controlled access to private variables.
Explain what getter and setter methods are and why they are useful in C++ classes.
Think about how to safely read and change private variables.
You got /4 concepts.
Write a simple C++ class with a private string variable and add getter and setter methods for it.
Remember getters return the variable, setters take a parameter to update it.
You got /4 concepts.