sammiiuu
sammiiuu

Reputation: 107

Why does a base class allows me to create an instance using a derived class constructor?

suppose we have this class structure:

public class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine("Base class constructor has been called.");
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        Console.WriteLine("Derived class constructor has been called.");
    }
}

so, my question is simple: Why does C# let me to create an instance of the Base class using the constructor of the Derived Class? for explample: BaseClass instance = new DerivedClass();

I would also like to know what is the effect of doing it or what would the benefits be of doing that? I know that if I execute this code, the base class constructor gets called first and then the derived constructor because this follows the normal behavior of class inheritance. thanks.

Upvotes: 1

Views: 70

Answers (2)

antlersoft
antlersoft

Reputation: 14786

You are not creating an instance of the base class; you are creating an instance of the derived class and storing a reference to it in a variable that has the type of the base class. A variable with a base type referencing an instance of the derived type is the basis of polymorphism.

Upvotes: 3

Adam Robinson
Adam Robinson

Reputation: 185643

You aren't; you're creating an instance of DerivedClass and storing a reference to that instance within a variable whose type is BaseClass. Any variable in C# (or virtually any object-oriented language) that is of type T can hold a reference (or pointer, depending on your language) to any object whose type is T or a type that derives from T at some point.

Doing this (in C#, anyway) has no effect whatsoever on how the object is constructed, so there is no "effect" in any strict sense.

Upvotes: 3

Related Questions