C# - How does CLR organize memory/reference during the inheritance?
.net, c#, inheritance, oop
Solution
(source: rvenables.com)
Yes, the derived class will also contain the base class fields in memory. On page 112 of CLR via C#, Jeffrey Richter says:
"Then, M3 executes its code to construct a Manager object. This causes an instance of the Manager type, a Manager object, to be created in the managed heap, as shown in Figure 4-9. As you can see, the Manager object-as do all objects-has a type object pointer and sync block index. This object also contains the bytes necessary to hold all of the instance data fields defined by the Manager type as any instance fields defined by any base classes of the Manager type (in this case, Employee and Object)." (Emphasis Added)
It's also worth noting that a separate block of memory is created for any base types. But ONLY for the type data (so only once, at most). When you create a Manager object (which derives from Employee), the CLR will ensure that there is a Manager Type Object, and an Employee Type Object on the heap.
1) Richter, Jeffrey. CLR via C#. Redmond: Microsoft Press, 2006. (Amazon Link)
Problem
Suppose i have the code snippet as follows : ( clarification purpose/not well formed) ``` class Employee { #region fields protected string _empID; protected string _empName; protected readonly string _ssn; #endregion public Employee(){} public Employee(string _empID,string _empName,string _ssn) { this._empID =_empID; this._empName=_empName; this._ssn = _ssn; } } class Manager : Employee { private string _branchID; public Manager(int _branchID):base(string _empID,string _empName,string _ssn) { this._branchID=_branchID; } } static void Main() { Manager mgr = new Manager("1","sam","xxx","Branch1"); } ``` Using base keyword I am invoking parent class constructor . In this case how the inheritance is organized? I have some bad assumptions as follow: As Manager is derived from Employee, Manager class is filled with (empID,empName,ssn) ``` ----------------- Manager ----------------- empID empName ssn branchID ``` step 1 : constructor invoking :base( "1","sam","xxx") step 2 : base class(Employee) constructor fills the derived class filed (empID,empName,ssn) step 3 : branchID is assigned by derived class constructor ....... My question is - If a class is derived from base class, the derived class also has the base class' hidden fields? - Derived class shares Base class fields? I mean separate memory block is allocated for Base class and derived class?