Home  >  Article  >  Backend Development  >  How does C++ function overloading achieve polymorphism?

How does C++ function overloading achieve polymorphism?

PHPz
PHPzOriginal
2024-04-13 12:21:01579browse

Function overloading can be used to achieve polymorphism, that is, calling a derived class method through a base class pointer, and the compiler selects the overloaded version based on the actual parameter type. In the example, the Animal class defines a virtual makeSound() function, and the Dog and Cat classes override this function. When makeSound() is called through the Animal* pointer, the compiler will call the corresponding overridden version based on the pointed object type, thus achieving polymorphism. sex.

C++ 函数重载如何实现多态性?

How does C function overloading achieve polymorphism

What is function overloading?

Function overloading is a programming technique that defines multiple functions with the same name but different parameter types or numbers in the same scope.

How to use function overloading to achieve polymorphism?

Polymorphism is a feature that allows calling derived class methods through a base class pointer or reference. The relationship between function overloading and polymorphism in C is as follows:

  • Function overloading allows the creation of multiple versions of a function with the same name but different signatures (types or number of parameters).
  • When a derived class method is called through a base class pointer or reference, the compiler selects the overloaded version to call based on the type of the actual parameter.

Practical example

The following code shows how to use function overloading to achieve polymorphism:

#include <iostream>

class Animal {
public:
    virtual void makeSound() {  // 声明为虚函数
        std::cout << "Animal sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {  // 重写 makeSound()
        std::cout << "Woof woof" << std::endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {  // 重写 makeSound()
        std::cout << "Meow meow" << std::endl;
    }
};

int main() {
    Animal* animalptr;  // 基类指针

    // 指向 Dog 对象
    animalptr = new Dog();
    animalptr->makeSound();  // 调用 Dog::makeSound()

    // 指向 Cat 对象
    animalptr = new Cat();
    animalptr->makeSound();  // 调用 Cat::makeSound()

    delete animalptr;

    return 0;
}

Output:

Woof woof
Meow meow

The above is the detailed content of How does C++ function overloading achieve polymorphism?. 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