Search code examples
c#argumentsprotected

"Does not contain a constructor that takes 0 arguments", and how to access protected values from another class


I have two issues. One is Box is inheriting values from Rectangle but I got the error "Does not contain a constructor that takes 0 arguments". What does it mean?

class Box : Rectangle
{
    private double height;
    private double Height
    {
        get { return height; }
        set { if (value > 0) height = value; }
    }

    //Error for box: Does not contain a constructor that takes 0 arguments
    public Box (double l, double w, double h)
    {
        length = l;
        width = w;
        height = h;
    }

    public double findArea(double h)
    {
        return h * h;
    }

    public double findVolume(double l, double w, double h)
    {
        return l * w * h;
    }

    public String toString()
    {
        return ("The volume is " + " cm");
    }
}

Another issue I cannot access protected values from the Rectangle class and I'm not sure how to go about that as well because I read and tried methods from other sites but I don't really understand.


Solution

  • Does not contain a constructor that takes 0 arguments

    This happens because your base class Rectangle does not in fact contain such a constructor, but you have not specified some other constructor to call. The parameterless constructor is the default when your class's constructor doesn't specify a base class constructor to call, but since one doesn't exist in the base class, you get a compile-time error.

    Inferring what the declaration of Rectangle is from the code you posted, I'm going to guess that you want your Box constructor to look like this:

    public Box (double l, double w, double h)
        : base(l, w)
    {
        height = h;
    }
    

    As for not being able to access protected members, that's simply not possible. The derived class always has access to any base class members that have protected accessibility. If you are having problems doing so, there's something else you're doing wrong.

    But without specifics about the problem, it's not possible to say what that is. You need to provide the exact error message you are getting, along with a good, minimal, complete code example that reliably reproduces the problem.