Does creating an instance of a child class create an instance of the parent class?

does it also automatically create an instance of the Parent class?

Not a separate instance; the ChildClass is a ParentClass instance, when talking about inheritance.

In words, this is like:

when creating a dog, do we also create an instance of an animal?

We don't create a dog and (separately) create an animal; the dog is the animal instance. And if we create a poodle, the poodle is the dog and is the animal.


No it doesn't but it calls the base constructor (the constructor of the parent class). Which in your case is empty, so the call to the base class constructor is done for you by the compiler:

class Program
{
    public class ParentClass
    {
        public ParentClass()
        {
            Console.WriteLine("ChildClass drived from me ");
        }

    }

    public class ChildClass : ParentClass
    {
        public ChildClass() : base() // base() call is voluntary
        {
            Console.WriteLine("This also use my Ctor");
        }
    }

    public static void Main()
    {
        ChildClass child = new ChildClass();
    }
}

However if your base class didn't have a parameterless constructor you would have to call it

class Program
{
    public class ParentClass
    {
        public ParentClass(string foo)
        {
            Console.WriteLine("ChildClass drived from me ");
        }

    }

    public class ChildClass : ParentClass
    {
        public ChildClass() : base("some foo") // base call is obligatory
        {
            Console.WriteLine("This also use my Ctor");
        }
    }

    public static void Main()
    {
        ChildClass child = new ChildClass();
    }
}

By definition when ChildClass inherits form ParentClass, then ChildClass objects belong to the ParentClass as well.

If your naming was more real-life oriented, it would be easier to understand.

class Animal {}
class Cat : Animal {}

var rocky = new Cat();

See, rocky is a cat, but it is an animal as well.


The actual answer to your question is

'No', it is an instance of the Child class, not of the Parent.

But if your question is: "Will you have an instance-object containing all properties of the Parent class", the answer is

'Yes', you will have all properties and fields that you have in the Parent class copied into the Child instance.

Tags:

C#

.Net