0
0
C++programming~20 mins

Default constructor in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Default Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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;
}
A0
B5
CCompilation error
DGarbage value
Attempts:
2 left
πŸ’‘ Hint
The default constructor sets length to a fixed value.
❓ Predict Output
intermediate
2: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;
}
A0,1
BGarbage,Garbage
CCompilation error
D0,0
Attempts:
2 left
πŸ’‘ Hint
The constructor uses an initializer list to set values.
πŸ”§ Debug
advanced
2: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;
}
AVariable 'a' is not declared
BMissing semicolon after class definition
CSyntax error: assignment outside constructor body
DConstructor missing return type
Attempts:
2 left
πŸ’‘ Hint
Look at how the constructor tries to assign a value.
❓ Predict Output
advanced
2: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;
}
ACompilation error: use of deleted function 'Test::Test()'
BProgram prints 0
CRuntime error
DProgram runs but does nothing
Attempts:
2 left
πŸ’‘ Hint
Deleting the default constructor disables object creation without arguments.
🧠 Conceptual
expert
2: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;?
ABoth x and y contain garbage values
BBoth x and y are initialized to zero
CCompilation error due to missing constructor
DBoth x and y are initialized to -1
Attempts:
2 left
πŸ’‘ Hint
Without a constructor, members are not initialized automatically.