Home  >  Article  >  Backend Development  >  How does inheritance achieve polymorphism in C++?

How does inheritance achieve polymorphism in C++?

WBOY
WBOYOriginal
2024-06-01 13:10:57240browse

In C++, polymorphism is achieved through inheritance, allowing objects to have different behaviors even if they have the same common base class. Inheritance is a method of creating new classes where the new class (derived class) inherits members from an existing class (base class) and can add new members. When a virtual function is called using a pointer or reference of a derived class type, the overridden method in the derived class is called.

C++ 中继承如何实现多态性?

How to implement polymorphism through inheritance in C++

What is polymorphism?

Polymorphism allows objects to have different behaviors even if they have the same common base class. In C++, polymorphism is achieved using inheritance.

Inheritance

Inheritance is a method of creating new methods of a class, where the new class (derived class) inherits from an existing class (base class). A derived class inherits all members (data and functions) of the base class and can also add new members of its own.

How is polymorphism achieved through inheritance?

In polymorphism, a derived class object can have a pointer or reference to its base class type. When a virtual function is called using a pointer or reference of a derived class type, the overridden method in the derived class is called.

Example:

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

class Dog : public Animal {
public:
    void makeSound() override {
        cout << "Woof woof!" << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        cout << "Meow meow!" << endl;
    }
};

int main() {
    Animal* animal = new Cat(); // 指向 Cat 对象的 Animal 指针
    animal->makeSound(); // 输出 "Meow meow!"
}

In the above example:

  • Animal is the base class.
  • Dog and Cat are derived classes.
  • makeSound is a virtual function, overridden in derived classes.
  • animal is a base class pointer pointing to a derived class object.

When animal->makeSound() is called, makeSound overridden in the derived class (Cat) will be called Method, output "Meow meow!".

The above is the detailed content of How does inheritance achieve polymorphism in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn