Challenge - 5 Problems
Class Syntax Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of simple class member access
What is the output of this C++ code?
C++
class Box { public: int length; Box(int l) { length = l; } }; int main() { Box b(5); std::cout << b.length << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Look at how the constructor sets the length and how it's accessed.
β Incorrect
The constructor sets length to 5, and b.length prints 5.
π Syntax
intermediate2:00remaining
Identify the syntax error in class definition
Which option contains a syntax error in the class definition?
C++
class Person { public std::string name; int age; };
Attempts:
2 left
π‘ Hint
Check the line with the access specifier.
β Incorrect
The 'public' keyword must be followed by a colon ':' not just a newline.
π§ Debug
advanced2:00remaining
Why does this class cause a compilation error?
Given the code below, why does it cause a compilation error?
C++
class Counter { private: int count; public: Counter() { count = 0; } void increment() { count++; } }; int main() { Counter c; c.count = 5; c.increment(); std::cout << c.count << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Check the access level of count and where it is accessed.
β Incorrect
The member 'count' is private and cannot be accessed directly in main.
π§ Conceptual
advanced2:00remaining
Class member initialization order
What will be the output of this code?
C++
class Test { public: int x; int y; Test() : y(10), x(y + 5) {} }; int main() { Test t; std::cout << t.x << ", " << t.y << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Members are initialized in the order they are declared, not the order in initializer list.
β Incorrect
x is initialized first with y's value before y is set to 10, so x gets garbage.
β Predict Output
expert2:00remaining
Output of class with static member
What is the output of this program?
C++
class Sample { public: static int count; Sample() { count++; } }; int Sample::count = 0; int main() { Sample a; Sample b; Sample c; std::cout << Sample::count << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
Static members are shared across all instances.
β Incorrect
Each constructor call increments count, so after 3 objects, count is 3.