Implementing Inheritance

Implementing Inheritance

Inheritance requires a base class and a derived class, where the derived class inherits from the base class. The members of the base class are inherited into the derived type. Derived classes can override and extend the interface inherited from the base type.

This is the syntax for inheritance syntax:

class derivedclass: baseclass, interface1, interface2, interfacen {
   derived body
}

In the class header, the colon stipulates inheritance and prefixes the base list. The base list is a comma-delimited list that includes at most one base class and any number of interfaces. Classes are limited to inheriting a single class. However, a class can inherit multiple interfaces. C++ developers are probably familiar with multiple inheritance. C++ allows multiple inheritance of classes. Excluding multiple inheritance was an important design decision for C#. Personally, I endorse that decision. First, multiple inheritance is not used that often. Second, multiple inheritance often causes more problems than are resolved. Third, multiple inheritance allows for the increased probability of ambiguousness of members.

A base type must have the same or greater accessibility than the derived type. A compiler error occurs in the following code. The accessibility of the base class is narrower than the derived class, which is an error.

internal class ZClass {
}
public class YClass: ZClass {
}

.NET supports only public inheritance. C++ supported public, protected, and private inheritance. Despite this flexibility in C++, practically all inheritance was public inheritance. Most C++ developers were not familiar with or ever used any other kind of inheritance. Thus, protected and private inheritance will probably not be missed.

Access Modifiers

Access modifiers set the visibility of members to the outside world and the derived type. Table 3-3 describes member accessibility.

Are private members of the base class inherited? Private members are indeed inherited but are not visible to the derived type and are not directly accessible in the derived class. These members are accessible through the public and protected functions of the base class. Therefore, a derived type has two realms of private variables. One realm includes private members that are defined in a derived class. These members are visible in the derived type. The other realm includes inherited private members, which are not visible to the derived type.