Challenge - 5 Problems
Data Members and Member Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of member function modifying data member
What is the output of this C++ program?
C++
class Counter { public: int count = 0; void increment() { count++; } }; int main() { Counter c; c.increment(); c.increment(); std::cout << c.count << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
The increment function increases the count by one each time it is called.
β Incorrect
The count starts at 0. Each call to increment() adds 1. After two calls, count is 2.
β Predict Output
intermediate2:00remaining
Output of const member function accessing data member
What will this program print?
C++
class Box { int length = 5; public: int getLength() const { return length; } }; int main() { Box b; std::cout << b.getLength() << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Const member functions can read data members but cannot modify them.
β Incorrect
The getLength() function returns the value of length which is 5.
β Predict Output
advanced2:00remaining
Output when accessing private data member directly
What happens when you try to compile and run this code?
C++
class Sample { private: int value = 10; public: int getValue() { return value; } }; int main() { Sample s; std::cout << s.value << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Private members cannot be accessed directly outside the class.
β Incorrect
The code tries to access private member 'value' directly, which is not allowed.
β Predict Output
advanced2:00remaining
Output of static data member shared across objects
What is the output of this program?
C++
class Tracker { public: static int count; Tracker() { count++; } }; int Tracker::count = 0; int main() { Tracker t1; Tracker t2; Tracker t3; std::cout << Tracker::count << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Static members are shared by all objects of the class.
β Incorrect
Each object increments the static count. After three objects, count is 3.
π§ Conceptual
expert2:00remaining
Effect of const member function on data members
Which statement is true about const member functions in C++?
Attempts:
2 left
π‘ Hint
Const member functions promise not to change the object except for mutable members.
β Incorrect
Const member functions cannot modify normal data members but can modify those declared mutable.