c# - with - Does creating an instance of a child class create an instance of the parent class?




types of inheritance in c# with example (5)

I'm new to C#, and I wanted to know, that if I create an instance of a child class, does it also automatically create an instance of the parent class or what?

Here is my code:

class Program
{

    public class ParentClass
    {
        public ParentClass()
        {
            Console.WriteLine("ChildClass uses my Ctor ");
        }

    }

    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine("SaySomething");
        }
    }

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

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.


Another way to think of a class is as just a template for objects. i.e object instances created from this class should have this implementation logic. Creating an instance of a class, takes all that logic and converts it into behavior for the object. When you inherit from some class, you're basically including the implementation logic of the parent class in the template of the child class, so you just get an extended 'template'. When you create an object instance from this template, the instance uses the child template, which contains a combination of the logic defined in the parent and the child classes.

Normal instantiation: class logic -> template -> instance

Inheritance: parent class logic + child class logic -> template -> instance


No it will only create an instace of the child class.


Talking specifically about your code:

class Program
{

    public class ParentClass
    {
        public ParentClass()
        {
            Console.WriteLine("ParentClass constructor is called");
        }

    }

    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine("ChildClassConstructor is called");
        }
    }

    public static void Main()
    {
        //will print that the Parent ctor is called, followed by printing that the child ctor is called
        ChildClass child = new ChildClass();

        //will print that the Parent ctor is called, followed by printing that the child ctor is called
        ParentClass childinparentbox = new ChildClass();

        //will print that the Parent ctor is called
        ParentClass parent = new ParentClass();

        //At this point there are 3 object instances in memory


        //by the way, this can't be done. Can't store a parent in a child: a parent is-not-a child
        ChildClass parentinchildbox = new ParentClass();


    }
}

I changed the messages to make them relevant to the point being made:

A constructor is just a method that is force-called whenever a new object is made. You use it to set the new object up for use, initialise properties etc. Classes are hierarchical in C# - everything is always a subclass of something, sometimes Object. Your parentClass is a child of Object, it just doesn't say. Your Child is declared a child of Parent

As others have noted, you don't get multiple instances of objects when you use new, you get one instance of whatever it was you asked to be created. Child classes can always be referred to/"stored inside" a variable that is declared to be a parent type. This is because things have an "is-a" relationship in the direction of Child -> Parent. A Dog is-a Animal, Cat is-a Animal, an Animal is-a Object. They don't have a relationship in the opposite direction.. You can't universally say a Car is-a Ferrari, or some Animal is-a Dog.

So, things chase back up the hierarchy, and you can store a Cat or a Dog inside a variable declared to hold an Animal. Animal might have a GetNumberOfLegs() method, that reports the number of legs. Cat and Dog would each return 4, Monkey would return 2.

One of the key tenets of object oriented programming is that you can refer to things in a generic way; all animals have some number of legs. If it's a Cat/Dog stored in the Animal, then GetNumberOfLegs() returns 4, if it's a Monkey it returns 2.. But you don't specifically need to know it's a cat, dog, monkey if all you are interested in is the number of legs. This will be covered more in coming lectures, so I don't need to get too deep into it here. I put this detail in as an explanation as to why we might even want to have a hierarchy, have an Animal, create a Dog and store it inside a variable of type Animal. We do it because often we want to refer to things in a generic way because we don't care about the specifics; we define the generic things we care about, and specific things fit the mold. You can drive a car; you don't need to be taught specifically how to drive a Ford or a Chevrolet - they have the steering wheel and pedals in the same place/arrangement. You can operate the generic interface. You don't care how the steering is implemented - hydraulic, rack and pinion, Pitman arm - you just care that when you turn the wheel "like this", the car goes "like that".

Getting back to what you asked:

Because Child is-a Parent is-a Object, when you make a new Child, you'll see a print out indicating the parent constructor was called and another indicating the child constructor was called. This doesn't indicate that 2 objects have been created in the memory of the computer - constructors are called in forward (root to tip) order for everything in the hierarchy starting with Object, then Parent, then Child. It's this way because the very first thing in any constructor's code, is a call to a relevant parent constructor. The first thing in that constructor's code, is a call to it's parent

So the runtime starts at the Child, then goes to the parent, the grandparent, great grandparent, all the way to the top of the ancestry, then comes back down, running the rest of the code in each constructor in order, top to bottom. This is why you see the printout that the Parent constructor was called, then you see the Child

It's all one and the same object, it's multiple method calls. Seeing two printouts isn't indicative of two objects in memory, it's one object with two methods (two constructor methods) that have been called in a recursive order


let say you have Parent Class Coffee and Child Class Cappucino

class Coffee {}

class Cappucino : Coffee {}

by issuing new Cappucino(), an instance is created for Cappucino. Cappucino is actually coffee and the properties of coffee is inherited to Cappucino.

No seperate instance is created for Coffee.

Cappucino carries features of Coffee by inheritance







.net