Make the frequent cases fast and the rare case correct

C# – Virtual Functions/methods vs Abstract functions/methods – (Polymorphism at work)

This article covers the fundamental object oriented concept of virtual function/method and also explain how it differs from abstract methods defined in abstract classes.

Polymorphism enables a derived class to override the behavior of a method of the base class. So many objects of different types can access same methods.

The following code shows how a method Blogger is overridden by a derived class to provide its own functionality. Also if a derived chooses not to override the virtual function and if a call is made then the base class method is executed.

Here is some insight into how a virtual function is different from an abstract method(of an abstract class).

A virtual function can exist in a abstract class or a normal class, while a abstract method exists in a abstract by using the ‘abstract’ keyword. An abstract class can provide complete, default code and/or just the details that have to be overridden. If a derived class inherits from an abstract class then it must provide an overriden implementation for the abstract method, however if a derived class inherits from a base class with a virtual function it does not require to implement it (for example derived2 class below). YOU MUST override a abstract method. So all abstract methods are virtual in the sense that they have to be overriden by the inheritor.

using System;
using System.Collections.Generic;
using System.Text;

namespace VirtualFunction
    class Base
        //virtual method in the base class.  
        public virtual void Blogger()
            Console.WriteLine("This is a Base Class blogger");

    class Derived1 : Base
        // Override Blogger()  
        public override void Blogger()
            Console.WriteLine("This is derived1 class blogger");

    class Derived2 : Base
        // This class does not override Blogger(). 

    class Program
        public static void Main()
            Base objBase = new Base();
            Derived1 objDerived1 = new Derived1();
            Derived2 objDerived2 = new Derived2();

            Base identify; // a reference to base class

            identify = objBase;

            identify = objDerived1;

            identify = objDerived2;
            identify.Blogger(); // since Blogger is not overriden, base class blogger is called 


This is a Base Class blogger
This is derived1 class blogger
This is a Base Class blogger

You can find the C++ version article here

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: