Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Base classes are automatically instantiated before derived classes

I want to know how Base classes are automatically instantiated before derived classes when we created derived class's instance.

I just want to know how base class's members occupied memory and child class's references access them.

like image 945
Abhishek Pandey Avatar asked Jun 18 '26 00:06

Abhishek Pandey


1 Answers

Lets have some examples:

class A
{
    int x;
    int y;
}

class B: A
{
    int c;
}

If you create a new instance of A, a piece of memory is create on the heap. This memory will be occupy 8 bytes; 4 bytes for x and 4 bytes for y. (I know, much more memory is reserved for its type, etc. but I will leave that outside this scope).

If you create a new instance of B, anohter piece of memory is created. Not two, only one. So no child instances or whatsoever. This piece of memory will by 12 bytes in length (4 bytes for x, 4 bytes for y and 4 bytes for the new field z.

When a piece of memory is created on the heap, it will always be filled with zero's. So all fieds will have their default value, in this case 0.

If both classes would have a public parameterless constructor, these constructors are called automatically.

class A
{
    int x;
    int y;
    public A()
    {
        x = 1; y = 2;     
    }
}

class B: A
{
    int c;
    public B()
    {
        z = 3;
    }
}

When a new instance of B is created, the constructor of B is called. The first thing that constructor does is call constructor of A. A will set its fields x and y to 1 and 2. Then the program returns to the constructor of B who will initialize z with the value 3.

The constructor of B could also have been written as (to show that B is calling the constructor of its base A):

    public B()
        : base()
    {
        z = 3;
    }
like image 67
Martin Mulder Avatar answered Jun 19 '26 14:06

Martin Mulder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!