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.
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:
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!