Bird
0
0

You want to create a class Rectangle that can be initialized with width and height, or with no parameters (defaulting to 1 for both). Which constructor setup is correct?

hard🚀 Application Q8 of 15
C Sharp (C#) - Classes and Objects
You want to create a class Rectangle that can be initialized with width and height, or with no parameters (defaulting to 1 for both). Which constructor setup is correct?
Apublic Rectangle() { Width = 1; Height = 1; } public Rectangle(int w, int h) { Width = w; Height = h; }
Bpublic Rectangle(int w, int h = 1) { Width = w; Height = h; }
Cpublic Rectangle() { Width = 1; Height = 1; } public Rectangle() { Width = 0; Height = 0; }
Dpublic Rectangle(int w, int h) { Width = w; Height = h; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor overloading for default and parameterized

    public Rectangle() { Width = 1; Height = 1; } public Rectangle(int w, int h) { Width = w; Height = h; } defines two constructors: one parameterless with defaults, one with parameters.
  2. Step 2: Check other options for correctness

    public Rectangle(int w, int h = 1) { Width = w; Height = h; } uses optional parameter but requires w so new Rectangle() fails; C duplicates parameterless constructors; D lacks parameterless constructor.
  3. Final Answer:

    public Rectangle() { Width = 1; Height = 1; } public Rectangle(int w, int h) { Width = w; Height = h; } -> Option A
  4. Quick Check:

    Overloaded constructors for defaults = B [OK]
Quick Trick: Use overloaded constructors for default and custom initialization. [OK]
Common Mistakes:
MISTAKES
  • Using optional parameters without allowing zero arguments
  • Defining duplicate parameterless constructors
  • Omitting parameterless constructor when needed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes