Section Relationship between Base Classes and Derived Classes
Base class: A base class is a class, in an object-oriented programming language, from which other classes are derived. The class which inherits the base class. Download scientific diagram | Relationship between base and derived classes. from publication: CHOPPA-M: Development, Capabilities and & Applications to. Relationship between Base and Derived Classes In this section, we use an inheritance hierarchy containing types of employees in a company's payroll.
We literally copied code from class CommissionEmployee and pasted it into class BasePlusCommissionEmployee, then modified class BasePlusCommissionEmployee to include a base salary and member functions that manipulate the base salary.
This "copy-and-paste" approach is often error prone and time consuming. Worse yet, it can spread many physical copies of the same code throughout a system, creating a code-maintenance nightmare. Is there a way to "absorb" the data members and member functions of a class in a way that makes them part of other classes without duplicating code? In the next several examples, we do exactly this, using inheritance. To avoid duplicating code and possibly errorsuse inheritance, rather than the "copy-andpaste" approach, in situations where you want one class to "absorb" the data members and member functions of another class.
Software Engineering Observation When changes are required for these common features, software developers need to make the changes only in the base classderived classes then inherit the changes. Without inheritance, changes would need to be made to all the source code files that contain a copy of the code in question.
Keyword public indicates the type of inheritance. As a derived class formed with public inheritanceBasePlusCommissionEmployee inherits all the members of class CommissionEmployee, except for the constructoreach class provides its own constructors that are specific to the class.
The derived class's public services also include member functions setBaseSalary, getBaseSalary, earnings and print lines BasePlusCommissionEmployee class definition indicating inheritance relationship with class CommissionEmployee. The constructor lines introduces base-class initializer syntax line 14which uses a member initializer to pass arguments to the base-class CommissionEmployee constructor.
Line 14 accomplishes this task by invoking the CommissionEmployee constructor by name, passing the constructor's parameters first, last, ssn, sales and rate as arguments to initialize base-class data members firstName, lastName, socialSecurityNumber, grossSales and commissionRate. Recall from Chapter 3 that the compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor.
Relationship between base class and derived class - CodeProject
However, CommissionEmployee does explicitly include a constructor, so a default constructor is not provided and any attempts to implicitly call CommissionEmployee's default constructor would result in compilation errors. The compiler generates errors for line 35 of Fig. Note that we used red text in Fig. The compiler issues additional errors at lines of BasePlusCommissionEmployee's print member function for the same reason. NET in this example. The error messages produced by your compiler may differ from those shown here.
Also notice that we highlight key portions of the lengthy error messages in bold. The errors in BasePlusCommissionEmployee could have been prevented by using the get member functions inherited from class CommissionEmployee. For example, line 35 could have invoked getCommissionRate and getGrossSales to access CommissionEmployee's private data members commissionRate and grossSales, respectively.
Similarly, lines could have used appropriate get member functions to retrieve the values of the base class's data members. In the next example, we show how using protected data also allows us to avoid the errors encountered in this example. Including the Base Class Header File in the Derived Class Header File with include Notice that we include the base class's header file in the derived class's header file line 10 of Fig. This is necessary for three reasons.
First, for the derived class to use the base class's name in line 12, we must tell the compiler that the base class existsthe class definition in CommissionEmployee. The second reason is that the compiler uses a class definition to determine the size of an object of that class as we discussed in Section 3. A client program that creates an object of a class must include the class definition to enable the compiler to reserve the proper amount of memory for the object.
When using inheritance, a derived-class object's size depends on the data members declared explicitly in its class definition and the data members inherited from its direct and indirect base classes.
Including the base class's definition in line 10 allows the compiler to determine the memory requirements for the base class's data members that become part of a derived-class object and thus contribute to the total size of the derived-class object. The last reason for line 10 is to allow the compiler to determine whether the derived class uses the base class's inherited members properly.
For example, in the program of Figs. Since these are inaccessible to the derived class, the compiler generates errors. The compiler also uses the base class's function prototypes to validate function calls made by the derived class to the inherited base-class functionsyou will see an example of such a function call in Fig.
The linking process is similar for a program that uses classes in an inheritance hierarchy. The process requires the object code for all classes used in the program and the object code for the direct and indirect base classes of any derived classes used by the program.
Suppose a client wants to create an application that uses class BasePlusCommissionEmployee, which is a derived class of CommissionEmployee we will see an example of this in Section When compiling the client application, the client's object code must be linked with the object code for classes BasePlusCommissionEmployee and CommissionEmployee, because BasePlusCommissionEmployee inherits member functions from its base class CommissionEmployee.
This provides the program with access to the implementations of all of the functionality that the program may use. As we discussed in Section Good Programming Practice The member-function implementations in Fig. CommissionEmployee class definition that declares protected data to allow access by derived classes.
CommissionEmployee class with protected data.
Because class BasePlusCommissionEmployee inherits from this version of class CommissionEmployee, objects of class BasePlusCommissionEmployee can access inherited data members that are declared protected in class CommissionEmployee i. As a result, the compiler does not generate errors when compiling the BasePlusCommissionEmployee earnings and print member-function definitions in Fig.
This shows the special privileges that a derived class is granted to access protected baseclass data members. In addition to the members that it inherits from Objectthe Publication class defines the following unique members and member overrides: Book ; However, its instance constructor can be called directly from derived class constructors, as the source code for the Book class shows.
Two publication-related properties Title is a read-only String property whose value is supplied by calling the Publication constructor. Pages is a read-write Int32 property that indicates how many total pages the publication has.
The value is stored in a private field named totalPages. Publisher-related members Two read-only properties, Publisher and Type. The values are originally supplied by the call to the Publication class constructor.
Publishing-related members Two methods, Publish and GetPublicationDate, set and return the publication date. The Publish method sets a private published flag to true when it is called and assigns the date passed to it as an argument to the private datePublished field. The GetPublicationDate method returns the string "NYP" if the published flag is false, and the value of the datePublished field if it is true.
Copyright-related members The Copyright method takes the name of the copyright holder and the year of the copyright as arguments and assigns them to the CopyrightName and CopyrightDate properties.
An override of the ToString method If a type does not override the Object. ToString method, it returns the fully qualified name of the type, which is of little use in differentiating one instance from another.
The Publication class overrides Object. ToString to return the value of the Title property. The following figure illustrates the relationship between your base Publication class and its implicitly inherited Object class. The Book class The Book class represents a book as a specialized type of publication. The following example shows the source code for the Book class. Two constructors The two Book constructors share three common parameters.
Inheritance in C# and .NET
Two, title and publisher, correspond to parameters of the Publication constructor. The third is author, which is stored to a public immutable Author property. One constructor includes an isbn parameter, which is stored in the ISBN auto-property. The first constructor uses the this keyword to call the other constructor. Constructor chaining is a common pattern in defining constructors. Constructors with fewer parameters provide default values when calling the constructor with the greatest number of parameters.
The second constructor uses the base keyword to pass the title and publisher name to the base class constructor. If you don't make an explicit call to a base class constructor in your source code, the C compiler automatically supplies a call to the base class' default or parameterless constructor.
The ISBN is stored in a private backing field, which is auto-generated by the compiler. A read-only Author property. The author name is supplied as an argument to both Book constructors and is stored in the property.
Two read-only price-related properties, Price and Currency. Their values are provided as arguments in a SetPrice method call. Both of these properties are externally read-only, but both can be set by code in the Book class. A SetPrice method, which sets the values of the Price and Currency properties.
Those values are returned by those same properties. Overrides to the ToString method inherited from Publication and the Object. Unless it is overridden, the Object. Equals Object method tests for reference equality. That is, two object variables are considered to be equal if they refer to the same object.
When you override the Object. Equals Object method, you must also override the GetHashCode method, which returns a value that the runtime uses to store items in hashed collections for efficient retrieval.
The hash code should return a value that's consistent with the test for equality. Since you've overridden Object. The following figure illustrates the relationship between the Book class and Publication, its base class. You can now instantiate a Book object, invoke both its unique and inherited members, and pass it as an argument to a method that expects a parameter of type Publication or of type Book, as the following example shows.
False Designing abstract base classes and their derived classes In the previous example, you defined a base class that provided an implementation for a number of methods to allow derived classes to share code.
In many cases, however, the base class is not expected to provide an implementation. Instead, the base class is an abstract class that declares abstract methods; it serves as a template that defines the members that each derived class must implement. Typically in an abstract base class, the implementation of each derived type is unique to that type.
You marked the class with the abstract keyword because it made no sense to instantiate a Publication object, although the class did provide implementations of functionality common to publications.
For example, each closed two-dimensional geometric shape includes two properties: The way in which these properties are calculated, however, depends completely on the specific shape.
The formula for calculating the perimeter or circumference of a circle, for example, is different from that of a triangle. The Shape class is an abstract class with abstract methods. That indicates derived classes share the same functionality, but those derived classes implement that functionality differently.
The following example defines an abstract base class named Shape that defines two properties: In addition to marking the class with the abstract keyword, each instance member is also marked with the abstract keyword. In this case, Shape also overrides the Object. ToString method to return the name of the type, rather than its fully qualified name. And it defines two static members, GetArea and GetPerimeter, that allow callers to easily retrieve the area and perimeter of an instance of any derived class.