Inheritance and Polymorphism in C++ - Tutorial

Welcome to this tutorial on inheritance and polymorphism in the C++ programming language. Inheritance is a powerful feature of object-oriented programming that allows you to create new classes (derived classes) based on existing classes (base classes). Polymorphism, on the other hand, enables objects of different types to be treated as objects of a common base type. In this tutorial, we will explore how to use inheritance and polymorphism in C++ to create hierarchical class structures and achieve dynamic behavior.

1. Inheritance and Base Classes

In C++, inheritance is achieved by using the `class` keyword followed by a colon and the access specifier (`public`, `protected`, or `private`). Here's an example:

      class Animal
      {
          protected:
              std::string name;
      public:
          void setName(const std::string& animalName)
          {
              name = animalName;
          }
          
          virtual void sound()
          {
              std::cout << "The animal makes a sound." << std::endl;
          }
  };
  
  class Dog : public Animal
  {
      public:
          void sound() override
          {
              std::cout << "The dog barks." << std::endl;
          }
  };
  
  int main()
  {
      Dog dog;
      dog.setName("Buddy");
      dog.sound();
      
      return 0;
  }

In the example above, we define a base class called `Animal` with a protected member variable `name` and two member functions `setName()` and `sound()`. We then create a derived class `Dog` that inherits from the `Animal` class using the `public` access specifier. The `Dog` class overrides the `sound()` function to provide a specific implementation.

2. Polymorphism and Virtual Functions

Polymorphism allows objects of different derived classes to be treated as objects of a common base class. To achieve polymorphic behavior, we use virtual functions. Virtual functions are declared in the base class and overridden in the derived classes. This allows the appropriate function to be called based on the actual object type at runtime. Here's an example:

      class Animal
      {
          protected:
              std::string name;
      public:
          void setName(const std::string& animalName)
          {
              name = animalName;
          }
          
          virtual void sound()
          {
              std::cout << "The animal makes a sound." << std::endl;
          }
  };
  
  class Dog : public Animal
  {
      public:
          void sound() override
          {
              std::cout << "The dog barks." << std::endl;
          }
  };
  
  int main()
  {
      Animal* animal = new Dog();
      animal->sound();
      
      delete animal;
      return 0;
  }

In this example, we create a pointer `animal` of type `Animal*` and assign it the address of a `Dog` object. By calling the `sound()` function through the `animal` pointer, the appropriate implementation of the function is invoked based on the actual object type, which is `Dog` in this case. This demonstrates polymorphic behavior.

3. Common Mistakes with Inheritance and Polymorphism

  • Forgetting to declare functions as `virtual` in the base class when intending to override them in derived classes.
  • Not properly managing memory when using polymorphic behavior with pointers. Remember to delete dynamically allocated objects.
  • Confusing public inheritance with private inheritance. Make sure to choose the appropriate access specifier when inheriting.

FAQs about Inheritance and Polymorphism in C++

  1. What is inheritance in C++?

    Inheritance is a feature in C++ that allows you to create new classes (derived classes) based on existing classes (base classes). The derived class inherits the properties and behaviors of the base class, allowing code reuse and the creation of hierarchical class structures.

  2. What is polymorphism in C++?

    Polymorphism is the ability of objects of different types to be treated as objects of a common base type. It allows you to write code that can work with objects of multiple derived classes through a base class interface, achieving dynamic behavior based on the actual object type.

  3. What is the difference between public, private, and protected inheritance?

    Public inheritance allows public and protected members of the base class to be accessible in the derived class. Private inheritance makes both the public and protected members of the base class private in the derived class. Protected inheritance makes the public and protected members of the base class protected in the derived class.

  4. Can a derived class inherit from multiple base classes?

    Yes, C++ supports multiple inheritance, which allows a derived class to inherit from multiple base classes. This enables the derived class to inherit properties and behaviors from multiple sources.

  5. What is the role of the `virtual` keyword?

    The `virtual` keyword is used to declare a function as virtual in the base class. This allows the function to be overridden in derived classes. When a virtual function is called through a base class pointer or reference, the appropriate derived class implementation is invoked based on the actual object type.

Summary

In this tutorial, we explored inheritance and polymorphism in C++. Inheritance allows you to create derived classes based on existing base classes, promoting code reuse and creating hierarchical class structures. Polymorphism enables objects of different types to be treated as objects of a common base type, allowing dynamic behavior based on the actual object type. We discussed how to declare derived classes, override functions, and achieve polymorphic behavior using virtual functions. It's important to be aware of common mistakes, such as forgetting to declare functions as virtual, managing memory properly, and understanding the access specifiers in inheritance. With a solid understanding of inheritance and polymorphism, you can write flexible and extensible code in C++.