Advertisements
Programmers seem to hate coding something from scratch; why code the same thing over and over again? Fortunately, it is possible to reuse code, thanks to one of the key concepts of object-oriented programming. That is inheritance, which is the subject of this article. So if you're looking for a clear explanation of how inheritance works in C++, keep reading.
Reusability is a key feature within our everyday life. Computers are a prime example of this. If you've learned some electronics, you probably know this, and if not, let me tell you that a dividing circuit can be made simply with just a few transistors. It will work much faster than the digital circuit you will find inside a calculator. The only problem with the analog solution is that if you want to multiply with it tomorrow, you have to rebuild the circuit, while the digital circuit can just be reprogrammed.
Before we venture deeper into this subject, let me specify that to understand this article fully you should know about classes (objects) and how you build them (private/public/protected members). First, we will present them.
The designers of object-oriented programming (in particular the creator of C++) thought in terms of reusability, and tried to implement a way to use code that is already written. If you have a family of objects that all have a few traits in common, why should you code separately for each of them?
It would be much more convenient to just write the common traits in a base class and later extend that with the specific objects. In the world of classes, inheritance solves this common problem. An object that holds the common traits and on which we will build the specific classes/objects is referred to as the base class, while the new class is known as the derived class.
For instance, let us perceive the group of geometrical shapes (a generic example). All geometrical items have a name, or if you stock them inside a database, you probably will want to point out each of them with a unique ID. The functions that let you set/get this data and the members that hold them are a common trait of the classes. Instead of coding these into each of the geometrical classes you will produce, why not inherit this from the base class?
class GeEntity
{
public:
GeEntity();
GeEntity(int ID, string name);
~ GeEntity();
protected:
string & name();
const string & name() const;
int& ID();
const int& ID() const;
private:
int m_ID;
string m_name;
};
There you have it. This code would require including all of the geometrical items like the square, circle, and so forth. Instead of adding this code for all of the classes, you can use inheritance and just write for the classes below this hierarchy the special/specific traits, and let them become heirs to the rest.
You can inherit by adding the ":" sign at declaration, followed by the class you are declaring:
class GeCircle : GeEntity
{
// write the class specifics };
Just like the member functions, variables can be of three types; inheritance can also be made in three different ways. The effect of the type of the inheritance you use will reflect on the inherited type's traits.
The table below shows how this works.
In order to explicitly specify the type of inheritance, you are going to need to add the public/private/protected keyword in front of the derived class. By default, this is private. Therefore, the correct way to inherit from the GeEntity is by using the public keyword:
class GeCircle : public GeEntity
{
// write the class specifics };
In this way we can use all of the base's members, just like we would if we own the class, unless that was private. Private members are not inherited regardless of the inheritance type because that would violate the private statement. It would not be private, as a derived class can access it freely. Specify protected access when you want to hide some functions from the user but not from its base classes. This lets you access any internal data/functions of the base class by the derived class and its friends.
Here it is important for you to understand the "is a" and "has a" relationship between classes. When an object inherits a class that is a type of the base class, it is that class; for example, a Circle is a Geometric Entity. But when you declare, as a member variable, a class inside a new class, you're looking at a "has a" relationship. A car has a steering wheel, one engine, and so forth. Private inheritance essentially provides another way to create the composition.
These are key concepts in object-oriented programming. In addition, you should note that no constructors, deconstructors, or base class operators will be inherited, as these are too specific to work generally on the hierarchy tree constructed by an inheritance. Look over the iostream hierarchy tree shown below.
This sums up the possibilities of inheritance inside C++ very well. The ios is the base class that holds common tasks for an input and output stream of data. These include details like where to store the data and how it is managed inside the stream.
The istream and ostream are specifications of the ios and are considered derived classes from the ios base class. As you may conclude, multiple inheritance is also possible, and you can individually set their access inheritance specifies. For example, you can set one public and the other protected (remember this is only for example purposes; this is implemented differently in the iostream library):
class iostream: public istream, protected ostream
{
// �
};
The method is to split them with a comma and specify for each of them what type of inheritance to execute. Remember that if you leave this empty, it's private inheritance by default. Multiple inheritances should be used carefully and only by experienced programmers, as they tend to be a little more complicated to maintain and code correctly.
The iostream class is the direct derived class of both the istream and ostream classes. If you climb up further in the hierarchy tree, the ios class is the indirect base of the iostream class.
While inheriting from the base classes, you may be tempted to specify protected access for the base variable members, so you can call them directly in the derived classes. As convenient as this may seem at first, I want to ring the warning bell; this is a dangerous practice, and one that can lead to error nodes and hard-to-maintain code.
Inheritance, to be efficient and software design friendly, should not provide direct access to the base class data. The point of inheritance is to provide services rather than dependency. By this, I mean that it should benefit from the base's functions only.
Suppose you declare a protected member variable in the base class. By definition, all classes derived from it, and friends of those, will have direct access to the variable. You will spare a few lines that you should have written for the get/set functions. Imagine now that you've finished the full hierarchy and implemented it into an application.
After a period, someone comes along, finds the name of the variable inappropriate, and changes it to a new one. Moreover, after this he simply tries to build the application. Countless errors will be generated if he forgot to change the names in the derived classes as well. Changing those is a troublesome task.
In addition, this is only the smaller issue. If you code in this fashion, you will find yourself in a situation where someone has changed the variable at a point and you have no tool with which to catch it.
The way I wrote the class on the first page is the solution. The members should always be private, so no one can access it besides the class itself, offering its services instead through the name and ID function.
The implementation looks like this:
int& GeEntity::ID()
{
return m_ID;
}
const int& GeEntity::ID() const
{
return m_ID;
}
Do it in the same way for the name also. These return the reference to the parameter both non-const and const so you can change and just read the data from the variables. If someone changes its value inappropriately, you can debug it easily by putting a break point inside the non-const call. It is simple and efficient.
Some people say that this will further slow down the application, because it will use a function call for accessing a variable and returning a value, wasting both CPU and memory. However, this is false. Today's compilers are smart enough to detect get/set functions and reference returns like this, and they will do the optimization.
At the compilation, there is a stage called inliner. This will take all functions that will not increase the size of the build significantly and put them directly inside the application. For instance, you may have a long function, although it is called only at a specific place. We can just take out that segment and put it where it is called, and economize a function call with absolutely no size change.
When you have a long function that is called a million times, for example, we had better leave it, as the extra size generated is too much to pay for. The compilers are once again behaving intelligently, striving to resolve situations like this. This encourages software engineering and a better readability/maintainability of the code.