Home >Backend Development >C++ >The role of C++ function return value types in polymorphism
In polymorphism, the function return value type specifies the specific object type returned when a derived class overrides a base class method. The return value type of a derived class method can be the same as the base class or more specific, allowing more derived types to be returned, thereby increasing flexibility.
The role of C function return value type in polymorphism
Introduction
Polymorphism is an important feature in object-oriented programming, which allows parent class references to point to objects of its subclasses. In polymorphism, the function return value type plays a key role, which determines the specific object type returned when a derived class overrides a base class method.
Polymorphism and return value types
When a derived class inherits a base class, the derived class can override the methods of the base class. If a base class method has a return value, the derived class method must have the same or more specific return value type as the base class method.
For example, consider the following base and derived classes:
class Shape { public: virtual Shape* clone() = 0; }; class Circle : public Shape { public: virtual Circle* clone() override; };
Shape
The base class defines a clone
method that returns a Shape
Object. Derived class Circle
overrides the clone
method and returns a more specific Circle
object.
Practical Case
The following is a practical case that shows the role of C function return value type in polymorphism:
#include <iostream> class Animal { public: virtual std::string speak() = 0; }; class Dog : public Animal { public: std::string speak() override { return "Woof!"; } }; class Cat : public Animal { public: std::string speak() override { return "Meow!"; } }; int main() { Animal* animal = new Dog; std::cout << animal->speak() << std::endl; // 输出: Woof! animal = new Cat; std::cout << animal->speak() << std::endl; // 输出: Meow! return 0; }
In this example , the Animal
base class defines a speak
method, which returns a string representing an animal's sound. Derived classes Dog
and Cat
override the speak
method and return the specific bark string.
The main function creates a Animal
pointer and points to the above derived class object. Due to the polymorphic nature, the program can call the speak
method of the derived class and get the correct scream output.
The above is the detailed content of The role of C++ function return value types in polymorphism. For more information, please follow other related articles on the PHP Chinese website!