Return type of an overriding virtual member function

Once declared virtual, a member function can be overridden in any level of derivation, as long as the overriding version has the identical signature of the original declaration. This is quite straightforward, but sometimes a virtual has to return an object of type that differs from the return type declared in its base class. The C++ Standard allows that only when the return type is replaced with a class publicly derived from the original return type. For example:

 class B {	virtual B* clone () const { return new B; }}class D {	void* clone () const { return new B; } //error; return type
//differs
D* clone () const { return new D; } //OK, D is publicly
//derived from B
}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: