Look at this C++ class with a constructor. What will the program print?
class Box { public: int length; Box(int l) { length = l; } }; int main() { Box b(10); std::cout << b.length << std::endl; return 0; }
Constructors set initial values when an object is created.
The constructor Box(int l) sets length to 10 when b is created. So, printing b.length outputs 10.
Which of these best explains why constructors are needed in C++?
Think about what happens when you create a new object.
Constructors run automatically when an object is created to set initial values or perform setup tasks.
Consider this C++ class without a constructor. What will be the output?
class Point { public: int x; }; int main() { Point p; std::cout << p.x << std::endl; return 0; }
What happens to uninitialized variables in C++?
Without a constructor, p.x is uninitialized and contains a garbage value.
Find the reason for the compilation error in this C++ code:
class Car { public: int speed; Car() { speed = 0; } }; int main() { Car c; std::cout << c.speed << std::endl; return 0; }
Check punctuation inside the constructor.
The line speed = 0 is missing a semicolon, causing a syntax error.
Choose the best reason why constructors are preferred for initializing objects in C++.
Think about safety and convenience when creating objects.
Constructors guarantee that objects start with valid values, preventing bugs from uninitialized data.