Home >Backend Development >C++ >When Can C Virtual Functions Have Covariant Return Types?
Covariant Return Types in C Virtual Functions
In C , it is possible for inherited classes to implement virtual functions with different return types. However, these return types must be covariant with the original return type.
Covariance means that the return type in the derived class is at least as derived as the return type in the base class. For example, if the base class function returns a Base pointer, the derived class function can return a Derived pointer.
This is allowed because any pointer to a derived class object is implicitly convertible to a pointer to a base class object. Therefore, a call to a virtual function in a base class can always return a pointer to a base class object, even if the derived class implementation returns a pointer to a derived class object.
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 clone that returns a Base pointer. In the Derived class, the clone function is overridden to return a Derived pointer. This is allowed because Derived is a derived class of Base, and a Derived pointer can be implicitly converted to a Base pointer.
The above is the detailed content of When Can C Virtual Functions Have Covariant Return Types?. For more information, please follow other related articles on the PHP Chinese website!