C# Programming - Inheritance - Discussion

Discussion Forum : Inheritance - General Questions (Q.No. 4)
4.
What will be the size of the object created by the following C#.NET code snippet?
namespace IndiabixConsoleApplication
{ 
    class Baseclass
    {
        private int i; 
        protected int j; 
        public int k;
    }
    class Derived: Baseclass
    {
        private int x; 
        protected int y; 
        public int z;
    }
    class MyProgram
    { 
        static void Main (string[ ] args)
        { 
            Derived d = new Derived();
        } 
    } 
}
24 bytes
12 bytes
20 bytes
10 bytes
16 bytes
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
28 comments Page 1 of 3.

Narendra said:   5 years ago
The size of a derived class object is equal to the sum of sizes of data members in base class and the derived class.

Sridhar said:   5 years ago
Not getting this. Please explain in a correct way.

Anju said:   5 years ago
By default, int is int32 in C# which takes 4 bytes.

6 fields get inherited to the class even though two can't be used.

So 6*4 =24 bytes.

Sunil said:   7 years ago
But we cannot access the protected member in the object of derived class. So memory does not occupy by this.

So, 4+4() is base class and (4+4) is derived class.

Vikas Verma said:   7 years ago
A size of int is 4.

How to check?

Console.WriteLine(sizeof(int));

Sol- 4

Raghupati Gupta said:   7 years ago
How will value 24 Byte?

Adi said:   8 years ago
How to check object memory?

Nithyapriya said:   8 years ago
For integer 4 similarly double, float, char. What is the value for this and all?

Shelja said:   8 years ago
Each integer (int) type data requires 4 bytes since in this program total 6 int data type variables are given.

Hence we can calculate the required memory for object by multiplying number of int variable and the 4 bytes memory required by each variable that is 6*4=24. :).

Vishwajeet Awasthi said:   8 years ago
If you make object of derived class then first the object of base class will be instantiated then after that the object of derive class will be instantiated. So in this case:

First---
Class BaseClass
{
private int i; (4 bytes)
protected int j; (4 bytes)
public int k; (4 bytes)
}

=12 bytes.

Class BaseClass
{
private int i; (4 bytes)
protected int j; (4 bytes)
public int k; (4 bytes)
}

=12 bytes.

And as I explained earlier if derived class is instantiated then automatically the object of base class is instantiated firstly. So, 12+12 = 24 bytes.


Post your comments here:

Your comments will be displayed after verification.