Sunday, June 2, 2013

Virtual class Modifier

The Virtual modifier is used to specify that a method or property can be overridden in the derived child class. Unlike the other class modifiers which are used at the class level , the virtual modifier cannot be used at the class level, instead it is used to modify the behavior of the functions and properties of the class.

The following example defines a class with a virtual function which is overridden in the derived class.
    class VirtualBaseClass
    {
        public void NormalFunction()
        {

        }
        //
        public virtual void VirtualFunction()
        {
           
        }
    }
    //
    class VirtualChildClass : VirtualBaseClass
    {
        public override void NormalFunction()
        {

        }
        //
        public override void VirtualFunction()
        {

        }
    }


In the above example we are also trying to override the non-virtual function in the derived class but this will result in the following compiler error.

Error: VirtualChildClass.NormalFunction()': cannot override inherited member 'VirtualBaseClass.NormalFunction()'  because it is not marked virtual, abstract, or override

Search Flipkart Products:
Flipkart.com

No comments: