Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differing return type for virtual functions

A virtual function's return type should be the same type that is in base class, or covariant. But why do we have this restriction?

like image 251
amit Avatar asked Jan 28 '11 08:01

amit


People also ask

Can virtual function have different return type?

The return type of an overriding virtual function may differ from the return type of the overridden virtual function. This overriding function would then be called a covariant virtual function. Suppose that B::f overrides the virtual function A::f .

Where the virtual function should be different?

Where the virtual function should be defined? Explanation: The virtual function should be declared in base class. So that when the derived class inherits from the base class, the functions can be differentiated from the one in base class and another in derived class.

Do virtual functions need to be overriden?

¶ Δ A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax.


1 Answers

Because of the nonsense that would ensue:

struct foo
{
    virtual int get() const { return 0; }
};

struct bar : foo
{
    std::string get() const { return "this certainly isn't an int"; }
};

int main()
{
    bar b;
    foo* f = &b;

    int result = f->get(); // int, right? ...right?
}

It isn't sensible to have a derived class return something completely unrelated.

like image 181
GManNickG Avatar answered Oct 06 '22 00:10

GManNickG