1

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.