Virtual Function Return Type in C
Question:
Can an inherited class implement a virtual function with a different return type without using a template as return?
Answer:
In certain cases, yes. It is permissible for a derived class to override a virtual function with a different return type, provided that the return type is covariant with the original return type. Covariance means that the return type of the derived function is a subtype of the return type of the base function.
Consider the following example:
class Base { public: virtual ~Base() {} virtual Base* clone() const = 0; }; class Derived: public Base { public: virtual Derived* clone() const { return new Derived(*this); } };
In this example, the Base class defines a pure virtual function named clone that returns a Base*. The Derived class overrides this virtual function and returns a Derived*. Even though the return type is different from the base class, this is valid because Derived* is a subtype of Base*.
In general, the return type of a function is not considered part of its signature. As long as the return type is covariant, you can override a member function with any return type.
The above is the detailed content of Can a Derived Class Override a Virtual Function with a Different Return Type in C ?. For more information, please follow other related articles on the PHP Chinese website!