Challenge - 5 Problems
Master of Classes and Objects
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of class method call
What is the output of this C++ program?
C++
#include <iostream> class Counter { public: int count = 0; void increment() { count++; } void print() { std::cout << count << std::endl; } }; int main() { Counter c; c.increment(); c.increment(); c.print(); return 0; }
Attempts:
2 left
π‘ Hint
Think about how many times the increment method is called before printing.
β Incorrect
The increment method increases the count by 1 each time. It is called twice, so count becomes 2. Then print outputs 2.
β Predict Output
intermediate2:00remaining
Value of object attribute after constructor
What will be the value of
obj.x after this program runs?C++
#include <iostream> class MyClass { public: int x; MyClass(int val) { x = val * 2; } }; int main() { MyClass obj(5); std::cout << obj.x << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Look at how the constructor sets the value of x.
β Incorrect
The constructor multiplies the input value by 2 and assigns it to x. So 5 * 2 = 10.
π§ Debug
advanced2:00remaining
Identify the error in this class definition
What error will this code produce when compiled?
C++
#include <iostream> class Sample { public: int value; Sample(int v) { value = v } }; int main() { Sample s(10); std::cout << s.value << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Check punctuation inside the constructor.
β Incorrect
The assignment line 'value = v' is missing a semicolon at the end, causing a syntax error.
β Predict Output
advanced2:00remaining
Output of method modifying object state
What is the output of this program?
C++
#include <iostream> class BankAccount { int balance; public: BankAccount() : balance(100) {} void deposit(int amount) { balance += amount; } void withdraw(int amount) { balance -= amount; } int getBalance() { return balance; } }; int main() { BankAccount acc; acc.deposit(50); acc.withdraw(30); std::cout << acc.getBalance() << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Calculate balance after deposit and withdrawal.
β Incorrect
Starting balance is 100. Deposit 50 makes it 150. Withdraw 30 leaves 120.
π§ Conceptual
expert3:00remaining
Number of objects created and output
Consider this program. How many objects are created and what is the output?
C++
#include <iostream> class Item { public: static int count; Item() { count++; } }; int Item::count = 0; int main() { Item a; Item b; Item c = b; std::cout << Item::count << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Copy construction uses the implicit copy constructor, which does not execute the default constructor body.
β Incorrect
Three objects are created: a, b, and c (copy of b). The default constructor increments count for a and b. The copy constructor for c does not increment count, so output is 2.