Click here to Skip to main content
15,936,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have virtual method in Parent class and i am calling this method directly in Parent class constructor.

now when i am creating the object of child class and i am putting the debugger on the default Constructor on both then before the Executing the complete Block of child class Default constructor then why the Output dispaly method of child class which is override.



C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    public  class class1
    {
       public virtual void Display()
        {
            Console.WriteLine("In Side Parent class");
        }
       public class1()
        {
            Display();
        }
    }
    class Program : class1
    {
        public Program()
        {

        }
        public override void Display()
        {
          Console.WriteLine("Inside Chiled Class");
        }
        static void Main(string[] args)
        {
            Program p=new Program();
            Console.ReadLine();
        }
    }
}
Posted

1 solution

Because it is virtual. What you observed is the heart of OOP, without it OOP could not be OOP. Please see: http://en.wikipedia.org/wiki/Dynamic_dispatch[^].

The method Display is called indirectly, via the virtual method table: http://en.wikipedia.org/wiki/Virtual_method_table[^].

This is what makes late binding and, hence, polymorphism possible:
http://en.wikipedia.org/wiki/Late_binding[^],
http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29[^].

You example is very funny: you discovered OOP by a chance, as a result of pretty much random try. Congratulations! Unfortunately, the opposite case is more typical: some people manage to use classes, inheritance, even use the word "virtual" but never do any OOP, some people manage not to get it for years. :-(

—SA
 
Share this answer
 
Comments
Siddharth Rai 6-Jul-18 12:26pm    
thanking you so much sir.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900