Home > Backend Development > C++ > Can a Derived Class Override a Virtual Function with a Different Return Type in C ?

Can a Derived Class Override a Virtual Function with a Different Return Type in C ?

Susan Sarandon
Release: 2024-12-11 08:35:11
Original
712 people have browsed it

Can a Derived Class Override a Virtual Function with a Different Return Type in C  ?

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);
    }
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template