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?
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 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.
¶ Δ 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With