Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# inheritance questions

I am creating an abstract base class which have functions implemented by other classes. My doubts are as follows

1) Do i need give 'virtual' in front of every function which need to be overridden by the child classes? I see some examples without the virtual keyword and still they are open to be overridden.

2) I need to have a function which will be implemented in the base class and i dont want it to be overridden by the child classes. I added the 'fixed' keyword infront of that function. Compiler start complaining 'member' cannot be sealed because it is not an override. Am i doing any wrong here?

abstract public class ShapeBase
    {
        private ShapeDetails _shapedDetails;

        public CampusCardBase(ShapeDetails shDetails)
        {
            _shapedDetails= shDetails;
        }

        public virtual void Draw();
        public virtual float getWidth();
        public virtual void Swap();
        public virtual void Erase();

        public sealed ShapeDetails getShapeDetails()
        {
            return _shapedDetails;
        }


    };
like image 888
logeeks Avatar asked May 25 '11 07:05

logeeks


2 Answers

  1. For methods without implementations in an abstract class, use abstract as well:

    abstract public void Draw();
    abstract public float getWidth();
    abstract public void Swap();
    abstract public void Erase();
    
  2. Methods aren't overridable by default; they only allow derived classes to override if declared abstract, virtual or override (but not override sealed).

    Therefore you don't need to give getShapeDetails() any other modifiers than public:

    public ShapeDetails getShapeDetails()
    {
        return _shapedDetails;
    }
    

On a side note, you should stick with .NET naming conventions and capitalize method names using Pascal case, so getWidth() becomes GetWidth() and getShapeDetails() becomes GetShapeDetails().

In fact you should be using a property getter for your _shapedDetails field instead of a getShapeDetails() method:

private ShapeDetails _shapedDetails;

public ShapeDetails ShapedDetails
{
    get { return _shapedDetails; }
}
like image 140
BoltClock Avatar answered Sep 19 '22 13:09

BoltClock


To be overrideable, a member must be marked virtual or abstract. If abstract, the class must also be abstract, and the member has no implementation in the defining class. A virtual member must provide an implementation. Derived classes must override abstract members and may override virtual members. Non-virtual members may not be "sealed" because they can't be overridden anyway.

like image 42
phoog Avatar answered Sep 19 '22 13:09

phoog