Is the derived class method called by the base class instance or the derived class instance?

advertisements

A derived class has access to base class method, so when base class method is called on derived class instance then is it really using derived class instance or is it using base class instance behind the scenes as we know that when derived class is intialized, it intializes its base also.

Consider below example, though it is part of virtual/new but this question came to mind when saw this.

 class Car
{
    public void DescribeCar()
    {
        System.Console.WriteLine("Four wheels and an engine.");
        ShowDetails();
    }

    public virtual void ShowDetails()
    {
        System.Console.WriteLine("Standard transportation.");
    }
}

class ConvertibleCar : Car
{
    public new void ShowDetails()
    {
        System.Console.WriteLine("A roof that opens up.");
    }
}

ConvertibleCar car2 = new ConvertibleCar();
car2.DescribeCar();

So when we do this, the base class "ShowDetails()" is called even though the instance is of derived class.

So behind scenes, is it using base class instance. Also when we "override" the ConvertibeCar showdetails i.e override the derived class method then it calls the derived class "showdetails()"


The whole point of overriding methods in sub-classes is that the method of the sub-class would get executed in run-time, even if the compile time type is that of the super-class.

If for some reason you require an instance of the super-class, you should add a copy constructor to your super-class and use it to create such an instance:

public class Base {
    ...
    ...
    Base (Base source) {
        // copy the properties
    }
}

Then:

public void makeStr(Derived d){
    Base b = new Base(d);
    ...
    b.getStr() will call the Base class implementation
}