Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derived class does not call base class method

class MyBaseClass
{
  virtual public void Print()
    {
      Console.WriteLine("This is the base class.");
    }
}

class MyDerivedClass : MyBaseClass
{
  override public void Print()
   {
     Console.WriteLine("This is the derived class.");
   }
 }

class Program
  {
    static void Main()
    {
      MyDerivedClass derived = new MyDerivedClass();
      MyBaseClass mybc = (MyBaseClass)derived;

      derived.Print();
      mybc.Print();

    }
   }

OUTPUT:

This is the derived class.
This is the derived class.

I do not understand why second call prints derived class's print() method because I cast mybc object to base class. I expect it to print base class print method instead. Am I missing something here?

like image 519
Lyrk Avatar asked Jun 10 '26 17:06

Lyrk


1 Answers

The variable type and the instance type are two different types. Casting does not change the instance type.

When you declare a method to be virtual/abstract, you're saying that you want the instance type to determine behavior when called.

Also note that this assignment is valid - cast syntax is not needed to change variable type from subclass to baseclass. This kind of cast can be done implicitly.

MyBaseClass mybc = derived;
like image 198
Amy B Avatar answered Jun 12 '26 12:06

Amy B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!