Challenge - 5 Problems
Default Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of default constructor initialization
What is the output of this C++ program?
C++
#include <iostream> class Box { public: int length; Box() { length = 5; } }; int main() { Box b; std::cout << b.length << std::endl; return 0; }
Attempts:
2 left
π‘ Hint
The default constructor sets length to a fixed value.
β Incorrect
The default constructor sets length to 5, so printing b.length outputs 5.
β Predict Output
intermediate2:00remaining
Default constructor with member initializer list
What will this program print?
C++
#include <iostream> class Point { int x, y; public: Point() : x(0), y(0) {} void print() { std::cout << x << "," << y << std::endl; } }; int main() { Point p; p.print(); return 0; }
Attempts:
2 left
π‘ Hint
The constructor uses an initializer list to set values.
β Incorrect
The default constructor sets x and y to 0 using the initializer list, so output is '0,0'.
π§ Debug
advanced2:00remaining
Why does this default constructor cause a compilation error?
Identify the reason this code does not compile.
C++
#include <iostream> class Sample { int a; public: Sample() a = 10; {} }; int main() { Sample s; return 0; }
Attempts:
2 left
π‘ Hint
Look at how the constructor tries to assign a value.
β Incorrect
The assignment 'a = 10;' is incorrectly placed outside the constructor body, causing a syntax error.
β Predict Output
advanced2:00remaining
Output when default constructor is deleted
What happens when you try to compile and run this code?
C++
#include <iostream> class Test { public: Test() = delete; }; int main() { Test t; return 0; }
Attempts:
2 left
π‘ Hint
Deleting the default constructor disables object creation without arguments.
β Incorrect
The default constructor is deleted, so creating 'Test t;' causes a compilation error.
π§ Conceptual
expert2:00remaining
Effect of default constructor on class member initialization
Consider this class with no user-defined constructor:
class Data {
int x;
int y;
};
What is the value of x and y after creating an object Data d;?
Attempts:
2 left
π‘ Hint
Without a constructor, members are not initialized automatically.
β Incorrect
Without a user-defined constructor, members are uninitialized and contain garbage values.