cpp inheritance

Inheritance and Polymorphism in C++

Current Status
Not Enrolled
Price
PRO
Get Started

Inheritance

Inheritance is one of the most important concepts of object-oriented programming. It makes it possible to divide complex problem areas into meaningful class hierarchies. Properties and capabilities that several classes possess are implemented only once in a superclass and inherited by one or more subclasses.

Thus, not only is code reused, but the logic of these properties and capabilities can be changed for all inheriting classes in a single place without having to change the code of each individual inheriting class.

C++ supports the concept of multiple inheritance. This means that a class can inherit from several base classes. In this case, each individual class is enumerated after the colon, separated by commas.

The inheriting classes are called superclasses or parent classes, while the inheriting classes are respectively called subclasses or child classes. The inheriting class extends the class from which it inherits, as it (usually) has properties and capabilities beyond those of the superclass.

Polymorphism

Methods can be subject to so-called polymorphism. Polymorphism is Greek and means multiformity. Polymorphism is spoken of in C++, for example, when two classes use the same method name, but the implementation of the methods differs.

Polymorphism is often used in inheritance, i.e. a variable can be assigned not only objects of the type of the class specified in the declaration, but also objects of the type of the child classes. This only works because each child class must also implement all methods and attributes of its parent classes.  This ensures that all child classes have the same methods as the parent class. However, the methods can be implemented differently, this is called “overwriting” the method.