Challenge - 5 Problems
Parameterized Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of parameterized constructor initialization
What is the output of this C++ program using a parameterized constructor?
C++
#include <iostream> using namespace std; class Box { int length; public: Box(int l) { length = l; } void show() { cout << length << endl; } }; int main() { Box b(10); b.show(); return 0; }
Attempts:
2 left
π‘ Hint
The constructor sets the length to the passed value.
β Incorrect
The parameterized constructor sets length to 10, so show() prints 10.
β Predict Output
intermediate2:00remaining
Value of member after parameterized constructor call
What is the value of member 'width' after this code runs?
C++
#include <iostream> using namespace std; class Rectangle { int width; public: Rectangle(int w) { width = w; } int getWidth() { return width; } }; int main() { Rectangle r(15); cout << r.getWidth() << endl; return 0; }
Attempts:
2 left
π‘ Hint
The constructor sets width to the passed value.
β Incorrect
The parameterized constructor assigns 15 to width, so getWidth() returns 15.
π§ Debug
advanced2:00remaining
Identify the error in parameterized constructor usage
What error does this code produce when compiled?
C++
#include <iostream> using namespace std; class Circle { int radius; public: Circle() { radius = 5; } Circle(int r) { radius = r; } void show() { cout << radius << endl; } }; int main() { Circle c(); c.show(); return 0; }
Attempts:
2 left
π‘ Hint
Look at how 'c' is declared in main.
β Incorrect
The line 'Circle c();' declares a function, not an object. So 'c.show()' causes a compilation error.
β Predict Output
advanced2:00remaining
Output of constructor with member initializer list
What is the output of this program?
C++
#include <iostream> using namespace std; class Point { int x, y; public: Point(int a, int b) : x(a), y(b) {} void display() { cout << x << "," << y << endl; } }; int main() { Point p(3, 4); p.display(); return 0; }
Attempts:
2 left
π‘ Hint
The member initializer list sets x and y to the passed values.
β Incorrect
The constructor initializes x=3 and y=4, so display prints '3,4'.
π§ Conceptual
expert3:00remaining
Behavior of parameterized constructor with default arguments
Consider this class with a parameterized constructor having default arguments. What will be the output of the program?
C++
#include <iostream> using namespace std; class Sample { int a, b; public: Sample(int x = 1, int y = 2) { a = x; b = y; } void print() { cout << a << "," << b << endl; } }; int main() { Sample s1; Sample s2(5); Sample s3(7, 8); s1.print(); s2.print(); s3.print(); return 0; }
Attempts:
2 left
π‘ Hint
Default arguments fill in missing parameters from right to left.
β Incorrect
s1 uses defaults (1,2), s2 uses 5 and default 2, s3 uses 7 and 8.