I want to clear my understanding of this basic OOPS concept in c#. On most of the internet sites, I read that a derived class inherits the private members of a base class, but it cannot access those members.
A derived class has access to the public, protected, internal, and
protected internal members of a base class. Even though a derived
class inherits the private members of a base class, it cannot access
those members. However, all those private members are still present in
the derived class and can do the same work they would do in the base
class itself. For example, suppose that a protected base class method
accesses a private field. That field has to be present in the derived
class in order for the inherited base class method to work properly.
Source : http://msdn.microsoft.com/en-us/library/ms173149.aspx
My question is, if we consider above is correct, then can we say "Constructors of base class are inherited in derived class, but derived class can only access/call it through its own constructor using base keyword and this constructor will not be available to outside world while creating instance of derived class".
public class Employee
{
public int salary;
public Employee(int annualSalary)
{
salary = annualSalary;
}
}
public class Manager : Employee
{
public Manager(int annualSalary)
: base(annualSalary)
{
//Add further instructions here.
}
}
Because to call a base class constructor, it should be present inside that class. Maybe my interpretation is wrong. Can anyone please explain this?
Thanks in advance!
Best Answer
It depends on how you define "present". If you define it as "somewhere available", private members in base classes are "present" as well as constructors. If you define "present" as "found in that particular class", both are not "present".
Try using reflection. You won't find any private members from base classes. The private members are inherited, thus available, but still only in the base class.
So are constructors.
At the end, you can say:
base
keyword. (A constructor is always called from each base class in the hierarchy. If not specified, it is the default constructor.)BindingFlags.FlattenHierarchy
to flatten visible members from base classes. Private members and constructors are only found in the declaring class.