Inheritance and polymorphism example demonstration in C + +

  • Share this:
post-title
In C + +, inheritance is a powerful feature that allows us to create one class and derive it from another. Through inheritance, we can reuse the functions of existing classes while adding or modifying new properties and methods. Polymorphism is another important feature of C + +, which allows us to dynamically bind function calls at runtime. In C + +, the key to implementing inheritance and polymorphism is to use virtual functions. A virtual function allows us to declare a pointer in the base class to the function in the derived class, so that we can override the function in the derived class to achieve polymorphism. Here is a simple example of how to use inheritance and polymorphism in C + +: ```cpp #include //base class class Base { public: virtual void print() { std::cout << "Base class" << std::endl;\n } }; //Derivative class class Derived : public Base { public: void print() override { std::cout << "Derived class" << std::endl;\n } }; int main() { Derived d; D.print () ;//output "Derived class" return 0;\n} ``` In this example, we define a base class called `Base`, which contains a virtual function called `print`. Then, we define a derived class named `Derived`, which inherits the `Base` class and rewrites the `print` function. Finally, in the `main` function, we create an instance of the `Derived 'class and call its `print` function to output "Derived class".
In C + + programming, inheritance and polymorphism are one of the core concepts of object-oriented programming (OOP).

By inheritance, we can create a base class (parent class) and derive multiple subclasses (derived classes) from this base class.

This mechanism allows us to reuse the code, and at the same time, it can realize dynamic binding at runtime through virtual functions and polymorphism mechanisms, making the program more flexible and scalable.

Below I will demonstrate how to use inheritance and polymorphism in C + + through a practical application scenario.

Suppose we want to design a simple animal classification system, including different kinds of animals such as cats, dogs and birds.

We will create a base class Animal, and then derived from this base class CatDogSumBirdThree subclasses.

Each subclass will have its own unique behaviors and attributes, but they will also share some common behaviors, such as eating and making sounds.

1. Define the base class Animal.

First, we define a base class Animal, which contains attributes and methods common to all animals:
pp
#include 
using namespace std;

class Animal {
public:
    string name;
    int age;

    Animal(string n, int a) : name(n), age(a) {}

    // 虚函数,使得可以在派生类中重新定义
    virtual void eat() {
        cout << name << " is eating." << endl;
    }

    virtual void makeSound() {
        cout << name << " makes a sound." << endl;
    }
};

In this base class, we define two member variables nameSumage, and two virtual functions eatSummakeSound

These virtual functions allow us to implement different behaviors in derived classes according to the characteristics of specific animals.

2. Define derived classes Cat, Dog, and Bird.

Next, we define three derived classes: CatDogSumBird

Each derived class inherits AnimalClass, and rewrite the virtual functions in it to implement specific behavior.

pp
class Cat : public Animal {
public:
    Cat(string n, int a) : Animal(n, a) {}

    void eat() override {
        cout << name << " is eating fish." << endl;
    }

    void makeSound() override {
        cout << name << " says Meow!" << endl;
    }
};

class Dog : public Animal {
public:
    Dog(string n, int a) : Animal(n, a) {}

    void eat() override {
        cout << name << " is eating bones." << endl;
    }

    void makeSound() override {
        cout << name << " says Woof!" << endl;
    }
};

class Bird : public Animal {
public:
    Bird(string n, int a) : Animal(n, a) {}

    void eat() override {
        cout << name << " is eating seeds." << endl;
    }

    void makeSound() override {
        cout << name << " says Tweet!" << endl;
    }
};

In each derived class, we override eatSummakeSoundMethods to simulate the specific behavior of different animals.

For example, cats eat fish, dogs eat bones, and birds eat seeds; cats call "meow", dogs call "wang", and birds call "chirp".

3. Use polymorphism to handle dynamic binding.

Now, we can create different types of animal objects and call their methods through pointers or references to the base class.

Due to the use of virtual functions, the program will be dynamically bound to the correct method implementation at runtime.

pp
int main() {
    Animal* animals[3];
    animals[0] = new Cat("Whiskers", 3);
    animals[1] = new Dog("Rex", 5);
    animals[2] = new Bird("Tweety", 2);

    for (int i = 0; i < 3; i++) {
        animals[i]->eat();
        animals[i]->makeSound();
    }

    for (int i = 0; i < 3; i++) {
        delete animals[i];
    }

    return 0;
}

In this example, we create a pointer to AnimalType pointer array, and store different types of animal objects in this array.

When we traverse the array and call eatSummakeSoundMethod, the program will call the corresponding method implementation according to the actual type of the object.

That's the beauty of polymorphism — it allows us to do the right thing without knowing the exact type of the object.

4. Summary.

From the above example, we can see how inheritance and polymorphism work together in C + +.

Inheritance allows us to reuse the code of the base class, while polymorphism allows us to dynamically select the correct method implementation at runtime.

This mechanism not only improves the maintainability and scalability of the code, but also makes the program more flexible and easier to understand.

In actual development, the rational use of inheritance and polymorphism can help us build more powerful and efficient applications.