Bird
Raised Fist0
C++programming~20 mins

Getter and setter methods in C++ - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Getter and Setter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of getter and setter usage in C++ class

What is the output of this C++ program that uses getter and setter methods?

C++
#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;
}
A10
B0
CCompilation error
DGarbage value
Attempts:
2 left
πŸ’‘ Hint

Check what value is assigned by the setter before calling the getter.

❓ Predict Output
intermediate
2:00remaining
Effect of missing setter call on getter output

What will this program print if the setter is never called?

C++
#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;
}
A0
B5
CCompilation error
DGarbage value
Attempts:
2 left
πŸ’‘ Hint

Look at the default value of the private variable.

πŸ”§ Debug
advanced
2:00remaining
Identify the error in getter and setter methods

What error will this code produce when compiled?

C++
#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;
}
ANo error, output is 7
BRuntime error: uninitialized variable
CCompilation error: calling non-const method on const object
DCompilation error: cannot call non-const setter from const method
Attempts:
2 left
πŸ’‘ Hint

Check if const correctness is properly used.

πŸ“ Syntax
advanced
2:00remaining
Which option causes a compilation error in getter/setter?

Which of the following setter method definitions will cause a compilation error?

Avoid setLength(int l) { length = l; }
Bvoid setLength(int l) override { length = l; }
Cvoid setLength(int l) noexcept { length = l; }
Dvoid setLength(int l) const { length = l; }
Attempts:
2 left
πŸ’‘ Hint

Consider what const means for member functions.

πŸš€ Application
expert
3:00remaining
Determine the final value after multiple setter calls

Given the following code, what is the final output?

C++
#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;
}
A5
B-3
C10
D0
Attempts:
2 left
πŸ’‘ Hint

Notice the condition inside the setter method.

Practice

(1/5)
1. What is the main purpose of getter and setter methods in C++ classes?
easy
A. To control access to private variables safely
B. To make variables public automatically
C. To delete variables from the class
D. To print variable values directly

Solution

  1. Step 1: Understand encapsulation in classes

    Getter and setter methods are used to access and modify private variables safely without exposing them directly.
  2. Step 2: Identify the role of getters and setters

    Getters return the value, setters allow controlled modification, often with validation.
  3. Final Answer:

    To control access to private variables safely -> Option A
  4. Quick Check:

    Getter and setter = control access [OK]
Hint: Getters and setters protect private data access [OK]
Common Mistakes:
  • Thinking getters/setters make variables public
  • Confusing setters with printing functions
  • Assuming getters modify data
2. Which of the following is the correct syntax for a setter method in C++ to set a private integer variable age?
easy
A. int setAge() { return age; }
B. void setAge(int a) { age = a; }
C. void getAge(int a) { age = a; }
D. int age(int a) { age = a; }

Solution

  1. Step 1: Identify setter method signature

    A setter usually returns void and takes a parameter to set the private variable.
  2. Step 2: Match correct syntax

    void setAge(int a) { age = a; } matches: void return type, parameter int a, and sets age = a.
  3. Final Answer:

    void setAge(int a) { age = a; } -> Option B
  4. Quick Check:

    Setter = void + parameter + assign [OK]
Hint: Setter methods return void and take a parameter [OK]
Common Mistakes:
  • Using return type int for setter
  • Naming setter as getAge
  • Setter returning a value
3. What will be the output of the following code?
#include <iostream>
class Person {
private:
  int age;
public:
  void setAge(int a) { if(a >= 0) age = a; else age = 0; }
  int getAge() { return age; }
};

int main() {
  Person p;
  p.setAge(-5);
  std::cout << p.getAge();
  return 0;
}
medium
A. Garbage value
B. -5
C. 0
D. Compilation error

Solution

  1. Step 1: Analyze setter behavior with negative input

    The setter checks if the input is >= 0; if not, it sets age to 0.
  2. Step 2: Check what happens with -5

    Since -5 < 0, age is set to 0.
  3. Final Answer:

    0 -> Option C
  4. Quick Check:

    Negative input sets age to 0 [OK]
Hint: Setter validates input before setting value [OK]
Common Mistakes:
  • Assuming negative value is stored
  • Expecting garbage value from uninitialized variable
  • Thinking code won't compile
4. Identify the error in the following setter method and choose the correct fix:
class Box {
private:
  int length;
public:
  void setLength() { length = l; }
};
medium
A. Remove the method entirely
B. Change return type to int
C. Make length public instead
D. Add parameter int l to setLength method

Solution

  1. Step 1: Check setter method parameters

    The setter tries to assign 'l' but has no parameter 'l' defined.
  2. Step 2: Fix by adding parameter

    Adding 'int l' as a parameter allows passing the value to set length.
  3. Final Answer:

    Add parameter int l to setLength method -> Option D
  4. Quick Check:

    Setter needs parameter to assign value [OK]
Hint: Setter must have parameter to set value [OK]
Common Mistakes:
  • Forgetting to add parameter
  • Changing return type unnecessarily
  • Making variable public instead of fixing setter
5. You want to create a class Temperature that stores temperature in Celsius but only allows values between -273 and 1000. Which setter method correctly enforces this rule?
hard
A. void setTemp(int t) { if(t >= -273 && t <= 1000) temp = t; else temp = -273; }
B. void setTemp(int t) { temp = t; }
C. int setTemp(int t) { if(t >= -273) temp = t; return temp; }
D. void setTemp() { temp = 0; }

Solution

  1. Step 1: Understand the value range requirement

    Temperature must be between -273 and 1000 inclusive.
  2. Step 2: Check which setter enforces this range

    void setTemp(int t) { if(t >= -273 && t <= 1000) temp = t; else temp = -273; } checks the range and sets temp accordingly; others do not enforce limits properly.
  3. Final Answer:

    void setTemp(int t) { if(t >= -273 && t <= 1000) temp = t; else temp = -273; } -> Option A
  4. Quick Check:

    Setter validates range before setting [OK]
Hint: Use if-condition in setter to validate input range [OK]
Common Mistakes:
  • Not validating input range
  • Setter without parameters
  • Setter returning int instead of void
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard