0

I'm studying on abstract methods and abstract classes. I don't understand how the following code runs without a compiler error and prints stackoverflow. I expected that error because I don't understand how it knows to call Playput's chew() method. Could you explain?

Demo

using System;
                    
public class Program
{
    public static void Main()
    {
        new Platypus();
    }
}

abstract class Mammal 
{ 
    abstract public String chew(); 
    public Mammal() 
    { 
        Console.WriteLine(chew()); // Does this line compile?
    }
}

class Platypus : Mammal 
{ 
    override public String chew() 
    { 
        return "stackoverflow"; 
    }  
}
Fildor
  • 14,510
  • 4
  • 35
  • 67
Hax
  • 133
  • 9
  • This may be helpful https://stackoverflow.com/questions/3842102/c-sharp-polymorphism – Serg May 16 '22 at 12:56
  • @Fildor I wouldn't want to change the author's code. – Hax May 16 '22 at 12:58
  • 3
    This kind of functionality is usually implemented by generating a virtual method table https://en.wikipedia.org/wiki/Virtual_method_table – Konrad May 16 '22 at 12:58
  • Ah, so the comment is in the original code, that you are studying ... I see. – Fildor May 16 '22 at 12:59
  • @Fildor yes, thank you. If you can explain how it compiles and prints it in detail, I really appreciate. – Hax May 16 '22 at 13:00
  • I think, Guru's answer pretty much explains it. Just be aware, that this is not a good idea, however. The reason for that is also in that answer. – Fildor May 16 '22 at 13:03

1 Answers1

3

Mammal is an abstract class, i.e. can not be instantiated. abstract public String chew(); means that any concrete (i.e. non-abstract) inheritor should have chew implemented so when any instance of concrete Mammal inheritor is created it has callable chew method which can be called during construction (underlying mechanism is basically the same as with "ordinary" polymorphism via virtual-override).

Note that some static analysis tools will give you warning like "Virtual member call in a constructor" due to possibly of unexpected behavior due to the order of member initializations.

Related (including ones from the comments):

  1. Docs about C# polymorphism
  2. SO on C# polymorphism
  3. Virtual method table
Guru Stron
  • 102,774
  • 10
  • 95
  • 132