CPP Tutorials

Understanding Inheritance in C++

Welcome to the glamorous world of Understanding Inheritance in C++! Inheritance is a powerful concept that allows us to create new classes based on existing classes, inheriting their properties and methods. It’s like building a family tree where new classes inherit traits from their parent classes. In this article, we’ll explore why we need inheritance, what it is, and how we can use it to write more efficient and organized code. Get ready to unravel the magic of inheritance as we dive into its key principles and real-life applications. Let’s begin this exciting journey!

Why Do We Need Inheritance in C++?

Inheritance in C++ is a way to create new classes by reusing the properties and behaviors of existing classes. This concept is like inheriting qualities from your parents. Imagine you have a parent who is good at playing the guitar. When you learn to play the guitar, you can inherit some of their skills and techniques. Similarly, in programming, inheritance allows new classes to inherit attributes and methods from already defined classes.

Why Do We Need Inheritance?

  • Code Reusability: Inheritance lets us avoid rewriting the same code in multiple classes. We can create a common base class with shared attributes and methods, and then different subclasses can inherit from it. This way, we don’t need to start from scratch every time we create a new class.
  • Hierarchy and Organization: Inheritance helps create a clear hierarchy of classes. Just like you can categorize different musical instruments under “string instruments,” “wind instruments,” and so on, you can organize classes in a hierarchy. This makes the code more organized and understandable.
  • Efficiency: With inheritance, we can modify or add functionalities to existing classes without affecting their base functionality. This helps in maintaining code efficiently. For example, you might have a general class for “Vehicle” and then specific classes like “Car,” “Bus,” and “Truck” inheriting from it. If you want to add a new feature to all vehicles, you can do it in the base class, and it will apply to all derived classes.
  • Polymorphism: Inheritance is a key feature for achieving polymorphism, which allows objects of different classes to be treated as objects of a common base class. This leads to more flexible and versatile code. For instance, you can create a function that works on different types of vehicles (car, bus, etc.) because they all share a common base class.
  • Easy Maintenance: Inheritance simplifies the maintenance of code. When a change is needed, it often only requires modifications in the base class or specific subclasses. This reduces the chances of introducing errors throughout the entire codebase.

What Is Inheritance in C++?

Inheritance is a concept in C++ that allows a new class to inherit properties and behaviors from an existing class. This allows you to create a new class that is based on an existing class, reusing its attributes and methods while also adding new ones or modifying existing ones. This is a fundamental concept in object-oriented programming that promotes code reusability and hierarchy.

How Inheritance Works:
Inheritance involves two classes: the base class (also known as the parent class) and the derived class (or child class). The base class is the class that provides the common properties and methods, while the derived class is the one that inherits and extends these properties and methods.

Syntax:
Here’s a simple syntax to declare inheritance in C++:

C++
class Base {
    // base class members
};

class Derived : public Base {
    // derived class members
};

In this example, the ‘Derived‘ class is inheriting from the ‘Base‘ class using the ‘public‘ keyword.

Example:
Let’s consider an example where we have a base class ‘Vehicle‘ and a derived class ‘Car‘. The ‘Vehicle‘ class has properties like speed and methods like ‘start()‘ and ‘stop()‘. The ‘Car‘ class inherits these properties and methods and adds its own method ‘honk()‘.

C++
#include <iostream>
using namespace std;

class Vehicle {
public:
    int speed;

    void start() {
        cout << "Vehicle started." << endl;
    }

    void stop() {
        cout << "Vehicle stopped." << endl;
    }
};

class Car : public Vehicle {
public:
    void honk() {
        cout << "Car honked." << endl;
    }
};

int main() {
    Car myCar;
    myCar.speed = 60;
    myCar.start();
    myCar.honk();
    myCar.stop();

    return 0;
}

Output:

C++
Vehicle started.
Car honked.
Vehicle stopped.

Explanation:

  • Base and Derived Classes: The code defines two classes, “Vehicle” and “Car.” “Car” is derived from “Vehicle,” which means it inherits properties and methods from the base class.
  • Inheritance: The “Car” class uses a colon followed by “public Vehicle” to indicate that it inherits from the “Vehicle” class. This inheritance allows “Car” to access the “speed,” “start,” and “stop” functions of the “Vehicle” class.
  • Object Creation: In the “main” function, an object “myCar” of the “Car” class is created. This object has access to both the “Car” and “Vehicle” class methods.
  • Method Calls: Using “myCar,” the program sets the “speed” to 60, calls the “start” function to indicate the car’s starting, invokes the “honk” function to sound the car’s horn, and then calls the “stop” function to stop the car.
  • Output: When executed, the program outputs messages like “Vehicle started,” “Car honked,” and “Vehicle stopped,” demonstrating the inheritance relationship. This code showcases how a derived class can extend and use functionalities inherited from a base class.

Types Of Inheritance:-

  1. Single inheritance
  2. Multilevel inheritance
  3. Multiple inheritance
  4. Hierarchical inheritance
  5. Hybrid inheritance

Single inheritance

In C++, single inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and behaviors from only one parent class. This means that a derived class can have only one base class. Let’s break down the concept step by step.

Concept:
In single inheritance, you create a new class (called the derived class or subclass) that inherits the properties and methods of another class (called the base class or superclass). This relationship forms a parent-child hierarchy, where the derived class can access and use the features of the base class.

Syntax:

C++
class Base {
    // Base class members
};

class Derived : public Base {
    // Derived class members
};

Explanation:
The ‘Base’ class serves as the parent class, and the ‘Derived’ class is the child class that inherits from it. The keyword ‘public’ indicates that the inheritance is public, meaning the public members of the base class are accessible in the derived class.

Example:

C++
#include <iostream>
using namespace std;

class Animal {
public:
    void sound() {
        cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void sound() {
        cout << "Dog barks" << endl;
    }
};

int main() {
    Dog d;
    d.sound(); // Output: "Dog barks"

    return 0;
}

Output:

C++
Dog barks

Explanation:

  • Base Class and Method: The code includes a base class named ‘Animal’, which has a method named ‘sound’.
  • Inheritance: A derived class called ‘Dog’ is created, inheriting from the ‘Animal’ class. This means the ‘Dog’ class will have access to the ‘sound’ method from the ‘Animal’ class.
  • Method Override: The ‘sound’ method in the ‘Dog’ class is overridden. This means that the ‘Dog’ class provides its own implementation of the ‘sound’ method instead of using the one from the base ‘Animal’ class.
  • Custom Output: When an instance of the ‘Dog’ class is created and its ‘sound’ method is called, it outputs “Dog barks”. This is because the overridden method in the ‘Dog’ class specifies this custom behavior.
  • Polymorphism: This example demonstrates the concept of polymorphism, where the same method name ‘sound’ behaves differently in the base and derived classes. This allows for more specialized behavior in derived classes while maintaining a common interface through inheritance.

Benefits:

  • Code reusability: You can reuse code from the base class in the derived class.
  • Hierarchical organization: Classes can be structured hierarchically, making the code more organized and easier to understand.
  • Polymorphism: Single inheritance allows you to implement polymorphism, where derived classes can have their own versions of inherited methods.

Drawbacks:

  • Limited to one parent: A derived class can inherit from only one base class, which might limit flexibility in some scenarios.

Multilevel inheritance

Introduction:
Multilevel inheritance is a concept in C++ where a class can inherit properties and behaviors from another class, and then that derived class can be inherited by yet another class. This forms a hierarchy or chain of inheritance, allowing for the reuse of code and creating a structured relationship between classes.

How it Works:
In multilevel inheritance, there’s a base class, a derived class that inherits from the base class, and then another derived class that inherits from the second derived class. This creates a parent-child relationship where each derived class inherits properties and methods from both its immediate parent and the parent’s parent.

Syntax:

C++
class Base {
    // Base class members
};

class Derived1 : public Base {
    // Derived1 class members
};

class Derived2 : public Derived1 {
    // Derived2 class members
};

Code Example:

Let’s say we have a scenario where we want to model different types of vehicles. We can create a ‘Vehicle‘ base class and then derive classes like ‘Car‘ from it, which will inherit vehicle properties. Further, we can derive ‘SportsCar‘ from the ‘Car‘ class, forming multilevel inheritance.

C++
#include <iostream>
using namespace std;

class Vehicle {
public:
    void start() {
        cout << "Vehicle started" << endl;
    }
};

class Car : public Vehicle {
public:
    void drive() {
        cout << "Car is being driven" << endl;
    }
};

class SportsCar : public Car {
public:
    void race() {
        cout << "Sports car is racing" << endl;
    }
};

int main() {
    SportsCar ferrari;
    ferrari.start(); // Accessing Vehicle method
    ferrari.drive(); // Accessing Car method
    ferrari.race();  // Accessing SportsCar method
    return 0;
}

Output:

C++
Vehicle started
Car is being driven
Sports car is racing

Summary:
Multilevel inheritance helps in creating a well-organized structure for classes, allowing for code reusability and maintaining a clear hierarchy. It’s important to use it judiciously to avoid deep hierarchies and complex relationships between classes.

Multiple inheritance

Multiple inheritance is a concept in C++ where a class can inherit attributes and behaviors from multiple parent classes. It allows a derived class to inherit characteristics from more than one base class. This feature enhances code reusability and helps in creating complex class rankings.

Let’s break it down. Imagine you have different classes that represent different things, say a “Bird” class and a “Fish” class. Now, you want to create a new class called “FlyingFish” that can have both the abilities of a bird (to fly) and a fish (to swim). This is where multiple inheritance comes into play.

In C++, the syntax for multiple inheritance is simple. You list all the parent classes separated by commas in the class declaration. For example:

C++
class FlyingFish : public Bird, public Fish {
    // class members
};

In this example, the “FlyingFish” class is inherited from both the “Bird” class and the “Fish” class.

Code Example:

C++
#include <iostream>
using namespace std;

class Bird {
public:
    void fly() {
        cout << "Bird can fly." << endl;
    }
};

class Fish {
public:
    void swim() {
        cout << "Fish can swim." << endl;
    }
};

class FlyingFish : public Bird, public Fish {
public:
    void display() {
        cout << "FlyingFish can fly and swim." << endl;
    }
};

int main() {
    FlyingFish ff;
    ff.fly();
    ff.swim();
    ff.display();
    return 0;
}

Output:

C++
Bird can fly.
Fish can swim.
FlyingFish can fly and swim.

Explanation:

  • Inherited Methods: The “FlyingFish” class inherits the “fly()” method from the “Bird” class and the “swim()” method from the “Fish” class.
  • Combined Abilities: The “FlyingFish” class can access and use both the “fly()” and “swim()” methods due to multiple inheritance.
  • Method Overriding: If the “FlyingFish” class wants to modify the behavior of the inherited methods, it can do so by overriding them.
  • Method Integration: The “display()” method in the “FlyingFish” class combines the abilities of both the “Bird” and “Fish” classes, showcasing that it can both fly and swim.
  • Enhanced Functionality: Multiple inheritance allows creating specialized classes like “FlyingFish” that combine characteristics from multiple parent classes, enabling more versatile and feature-rich objects.

Hierarchical inheritance

Hierarchical inheritance is a concept in C++ where a derived class inherits from a single base class, and then one or more derived classes are created from this first derived class. In simpler terms, it’s like a family tree where the parent class is the base, and multiple child classes are derived from it, forming a hierarchy.

Let’s break this down:

Hierarchy Explanation:
In hierarchical inheritance, you have a base class, let’s say “Vehicle”. Now, you create two classes, “Car” and “Motorcycle”, which are both derived from the “Vehicle” class. Both “Car” and “Motorcycle” classes inherit the properties and behaviors of the “Vehicle” class.

Code Example:

C++
#include <iostream>
using namespace std;

// Base class
class Vehicle {
public:
    void display() {
        cout << "This is a Vehicle." << endl;
    }
};

// First derived class
class Car : public Vehicle {
public:
    void carInfo() {
        cout << "This is a Car." << endl;
    }
};

// Second derived class
class Motorcycle : public Vehicle {
public:
    void motorcycleInfo() {
        cout << "This is a Motorcycle." << endl;
    }
};

int main() {
    Car myCar;
    Motorcycle myMotorcycle;

    myCar.display();
    myCar.carInfo();

    myMotorcycle.display();
    myMotorcycle.motorcycleInfo();

    return 0;
}

Output:

C++
This is a Vehicle.
This is a Car.
This is a Vehicle.
This is a Motorcycle.

Explanation:

  • Base Class “Vehicle”: The starting point of the hierarchy is the base class “Vehicle”. It serves as a blueprint with common properties and behaviors.
  • Derived Classes “Car” and “Motorcycle”: Both “Car” and “Motorcycle” are derived classes that inherit from the “Vehicle” base class.
  • Specific Functions: Each derived class has its own specialized functions, such as “carInfo()” in the “Car” class and “motorcycleInfo()” in the “Motorcycle” class.
  • Accessing Base Class Functions: Despite having their own functions, both derived classes can also access the functions of the base class, demonstrated by calling “display()” from the “Vehicle” class.
  • Inheritance Hierarchy: This arrangement forms a hierarchical structure, where classes build upon each other, inheriting and extending functionalities.

Advantages of Hierarchical Inheritance:

  • Code reusability: The common features from the base class are inherited by multiple derived classes.
  • Structured design: Hierarchy helps in organizing classes and relationships in a structured manner.
  • Easy maintenance: If any change is made to the base class, it automatically affects all the derived classes.

Considerations:
While hierarchical inheritance can be useful, it’s important not to overcomplicate the hierarchy. It’s essential to maintain a clear and meaningful relationship between the classes in order to ensure code readability and maintainability.

Hybrid inheritance

Hybrid inheritance in C++ is a combination of two or more types of inheritance, typically single inheritance and multiple inheritance. This allows a class to inherit properties and behaviors from both base classes, resulting in a complex hierarchy of classes.

In hybrid inheritance, a class can inherit from multiple base classes, and these base classes can further inherit from other classes. This creates a network-like structure, enabling the derived class to access features from different inheritance paths.

Syntax:

C++
class Base1 {
    // Base1 class members
};

class Base2 {
    // Base2 class members
};

class Derived : public Base1, public Base2 {
    // Derived class members
};

Here, the ‘Derived‘ class inherits from both ‘Base1‘ and ‘Base2‘ classes. This is an example of hybrid inheritance.

Example:

C++
#include <iostream>
using namespace std;

class A {
public:
    void displayA() {
        cout << "This is class A" << endl;
    }
};

class B {
public:
    void displayB() {
        cout << "This is class B" << endl;
    }
};

class C : public A, public B {
public:
    void displayC() {
        cout << "This is class C" << endl;
    }
};

int main() {
    C obj;
    obj.displayA();
    obj.displayB();
    obj.displayC();

    return 0;
}

Output:

C++
This is class A
This is class B
This is class C

Explanation:

  • The example involves three classes: A, B, and C.
  • Class C is derived from both classes A and B, exhibiting hybrid inheritance.
  • The main function generates an instance of class C.
  • Functions from all three classes – A, B, and C – are invoked through the object.
  • This showcases the utilization of hybrid inheritance, enabling the combined use of functionalities from multiple base classes.

A Problem to Solve

Problem Statement:

You are working on a vehicle management system, and you need to categorize different types of vehicles, including Cars and Motorcycles.

  • Base Class (Vehicle): This class should contain common attributes like make, model, and year. It should have methods to set these attributes and a method to display them.
  • Derived Class (Car): This class is a specific type of vehicle and should inherit from the Vehicle class. In addition to the attributes from Vehicle, it should have additional attributes like number_of_doors and trunk_size. It should have methods to set these attributes and a method to display all the Car details, including the inherited attributes.
  • Derived Class (Motorcycle): This class is another specific type of vehicle and should inherit from the Vehicle class. In addition to the attributes from Vehicle, it should have additional attributes like helmet_included (a boolean indicating if a helmet is included) and type (e.g., “sport” or “cruiser”). It should have methods to set these attributes and a method to display all the Motorcycle details, including the inherited attributes.

Write a program that demonstrates the creation of both Car and Motorcycle objects. Make sure to set all their attributes and display all their details.

Guidelines:

  • Use public inheritance to create the Car and Motorcycle classes.
  • Utilize constructors for initialization and include appropriate getter and setter methods.
  • The display methods should use the display method from the Vehicle class to show common attributes, ensuring code reusability.

Sample Output:

For a Car object, you might display something like:

C++
Make: Honda
Model: Accord
Year: 2022
Number of Doors: 4
Trunk Size: Large

For a Motorcycle object, you might display something like:

C++
Make: Harley-Davidson
Model: Sportster
Year: 2023
Helmet Included: Yes
Type: Cruiser

The Pros and Cons of Using Inheritance

Pros of Using InheritanceCons of Using Inheritance
Allows code reusabilityThis can lead to tight coupling between classes
Helps create organized and efficient codeMay introduce bugs and errors if not used carefully
Promotes code extensibilityThis may increase the complexity of the code
Facilitates polymorphism, enabling dynamic behaviorMay increase the complexity of the code
Enhances readability and maintenanceOveruse of inheritance can make code harder to understand
The Pros and Cons of Using Inheritance

Key Takeaways

  • Behavior Reuse: Inheritance enables the creation of new classes based on existing ones. This allows the new class to inherit properties and methods from the parent class, saving time and effort by reusing already defined functionalities.
  • Behavior Extension: New classes can extend the behavior of the parent class by adding new methods or attributes. This provides a way to enhance or customize the functionality without modifying the original class.
  • Code Modularity: Inheritance promotes modular programming by allowing classes to be organized hierarchically. This makes code more organized, easier to manage and helps in isolating changes to specific areas.
  • Polymorphism: Inheritance is a key factor in achieving polymorphism, where different classes can be treated as instances of the same base class. This allows for more generic programming and the use of common interfaces.
  • Efficiency: Inheritance promotes efficient coding since it reduces redundancy. Common functionalities are defined in the base class, and subclasses only need to define specific behaviors, leading to cleaner and more maintainable code.

Conclusion

In conclusion, inheritance in C++ is a powerful tool that empowers programmers to create efficient and flexible programs. By mastering its concepts, you can enhance code reusability, create organized structures, and enable dynamic behaviors through polymorphism. However, careful use is crucial to avoid complexities and bugs. Keep practicing and honing your inheritance skills, and you’ll soon become proficient in crafting better software solutions. Happy coding!

FAQs

  • What is inheritance in C++?
    Inheritance in C++ is a process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.
  • Why do we use inheritance in C++?
    We use inheritance in C++ to create new classes that reuse, extend, and modify the behavior defined in other classes. It allows us to represent the “is-a” relationship between objects.
  • How do we use inheritance in C++?
    We use inheritance in C++ by creating a derived class from a base class. The derived class inherits all the properties and methods of the base class.
  • Can using inheritance make code more confusing?
    Yes, if you use inheritance incorrectly, it can lead to problems. It’s important to understand how inheritance works and when to use it.
  • What are some examples of using inheritance in C++?
    Some examples include using inheritance to create a Dog class from an Animal class, a Car class from a Vehicle class, or an Eagle class from a Bird class.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Index
Becoming a Full Stack Developer in 2023 How to Become a Software Engineer in 2023
Close

Adblock Detected

Please consider supporting us by disabling your ad blocker!