Popular
Data Science
Technology
Finance
Management
Future Tech
Does maintaining your C++ code turn into a nightmare that keeps getting worse as your project gets bigger?
We’ve all been there writing the same logic over again or trying to figure out how to structure code, so it’s easy to maintain.
That is, the inheritance in C++ comes into play.
Inheritance is the ability of a class to acquire the attributes and characteristics of a different class. One may see it as being much like the transfer of traits from parent to child, but in which the child is not an exact duplicate.
Inheritance is not a mere buzzword; it is the cornerstone of Object-Oriented Programming.
Now, let’s say we have to design some complicated system where each component has some common functionality. Rather than reinventing the wheel each time, we can define a base class with shared features and then have other classes inherit from it.
In this way, we save a little bit of time and make our code more maintainable.
Consider the development of a software system for the library.
We may have a superclass like LibraryItem that would hold fields like title, author, and ISBN. Then we could be able to create more generic classes, such as Book, Magazine, and DVD.
Each of these could inherit the common attributes while adding their particular features.
When it comes to C++ inheritance, it is important to know about the various types-public, protected, and private.
These modes will determine how the deriving class gets to access inherited stuff from the base class and, finally, how objects of the derived class can use them, too.
In public inheritance, though being the most commonly used form, all the public members of the base class remain public in the derived class, and ‘protected’ remains ‘protected’.
However, the private members are not directly accessible from the derived class, but if needed, they can be accessed through the public or protected methods of the base class.
Example:
Output:
In this example, the Car class publicly inherits from Vehicle, so brand and honk() are directly accessible in Car.
In protected inheritance, all the members that are public and protected in the base class become protected in the derived class.
It means they cannot be accessed from other classes apart from the derived class, but they can be accessed within the derived class and other sub-classes of the derived class.
Example:
Output:
Here, Employee inherits from Person using protected inheritance.
The name and age attributes, though set through a public method, are protected in Employee and can’t be accessed directly outside of it.
In private inheritance, both the public and protected members of base classes become private in the derived classes.
This implies that they can only be invoked by the derived class and not even by other sub-classes of that class.
Example:
Output:
Here, the Dog class privately inherits from Animal. The eat() function is accessible within Dog, but trying to call it outside of Dog results in an error.
In single inheritance, a derived class inherits from just one base class.
This is the most basic form of inheritance.
Imagine we have a base class called LibraryItem with common attributes like title and author. We can create a derived class called Book that adds more specific features like ISBN.
Example:
In this example, Book inherits from LibraryItem, making it easy to manage shared properties like title and author without rewriting code.
Output:
Sometimes, a single base class isn’t enough. We might need a class that combines features from more than one base class.
This is where multiple inheritance comes into play.
Consider creating a Smartphone class that inherits from both Camera and Phone. This lets us mix features like taking photos and making calls.
Example:
Output:
Here, the Smartphone inherits from both the Camera and Phone, enabling it to use functionalities from both classes.
What if we need a class that inherits from another derived class?
Multiple inheritance enables one class to inherit from another derived class, forming a hierarchy of inheritance.
Suppose we have a base class, Animal, a derived class, Mammal and another derived class – Human. These components are closely intertwined; each stage is constructed based on the previous one.
Example:
Output:
Here, Human inherits from Mammal, which in turn inherits from Animal. This creates a hierarchy where each class adds more specific functionality.
In hierarchical inheritance, multiple classes share the same base class. This is useful when different classes need to inherit the same basic features.
Imagine a base class Shape with derived classes like Rectangle, Circle, and Triangle. Each shape shares some common properties like area.
Example:
Output:
Here, Rectangle and Triangle share the base class Shape, allowing us to reuse the setDimensions method.
Hybrid inheritance combines more than one type of inheritance. This often happens when classes are part of a more complex system.
For example, we could combine single and multiple inheritance to create a class structure that manages devices.
Example:
Output:
In this example, AllInOne inherits from both the Printer and Scanner, which both inherit from the Device.
This allows AllInOne to use features from both classes while avoiding the diamond problem through virtual inheritance.
Have you ever faced a situation where two parent classes share a common base class?
If you have done so, you also likely have encountered what is called the diamond problem in C++ inheritance.
One such problem arises when a derived class is inheriting from two classes, and both classes are again inheriting from the same base class. This problem has been so named because the inheritance diagram drawn from this appears like a diamond.
Now, assuming for explanation purposes, let there be a base class Device, and then two derived classes Printer and Scanner, each derived from the base class Device.
Suppose, for example, we make another class, say, AllInOne, which inherits from both the classes Printer and Scanner. Again, this makes two copies of a Device to be in AllInOne.
This can lead to confusion and ambiguity, especially with access to the base class members.
This code won’t compile because the compiler doesn’t know whether to use the powerOn() method from Printer or Scanner.
To solve this, we use virtual inheritance.
By declaring the base class as virtual, we ensure that only one copy of the base class is inherited and hence avoiding the ambiguity.
Output:
Here, by making the Device a virtual base class, both the Printer and Scanner share a single copy of the Device.
This resolves the diamond problem, allowing AllInOne to call powerOn() without any ambiguity.
Inheritance in C++ offers significant advantages:
Also Check: C++ Tutorial
Suppose someone begins developing a Graphical User Interface (GUI); he or she has to conceptualise and code numerous elements, including buttons, text boxes, and sliders.
Although these components are very similar and have parameters such as position and size in common, they act differently.
Another advantage that comes from the creation of such classes as Widget is that we can create subclasses such as Button and TextField. This enables us to avoid writing the same code all over again and also makes our application more consistent.
Example:
Output:
Inheritance in C++ is all about code reuse and extension, as in any other OOP language. This turns out to be one of the ways of obtaining clean, scalable and maintainable code therefore managing complexities in systems.
It helps developers to create organised and well-structured codebases, thanks to the different forms of inheritance and its implications on access control.
Accomplished through effective use of inheritance, allowing the codebase to expand with the project, support additional features without losing manageability, and reduce the pains of updating later on.
Using inheritance is a smarter way of coding and allows us to get better while writing more powerful software.
The DevOps Playbook
Simplify deployment with Docker containers.
Streamline development with modern practices.
Enhance efficiency with automated workflows.
Popular
Data Science
Technology
Finance
Management
Future Tech
Accelerator Program in Business Analytics & Data Science
Integrated Program in Data Science, AI and ML
Certificate Program in Full Stack Development with Specialization for Web and Mobile
Certificate Program in DevOps and Cloud Engineering
Certificate Program in Application Development
Certificate Program in Cybersecurity Essentials & Risk Assessment
Integrated Program in Finance and Financial Technologies
Certificate Program in Financial Analysis, Valuation and Risk Management
© 2024 Hero Vired. All rights reserved