c++ - Override function that return base type -
c++ - Override function that return base type -
i have 2 classes. base of operations class parent , derived class child. class parent has pure virtual function returns class type. how can override in derived class?
class parent { public: virtual parent* overrideme(parent* func) = 0; }; class kid : public parent { public: child* overrideme(child* func) override; }; i tried child* overrideme(child* func) override; end error not override base of operations class member.
if c++ had total covariance , contravariance support, right relationship contravariant in input , covariant in output. namely:
struct organism { }; struct animal : organism { virtual animal* overrideme(animal* ) = 0; }; struct dog : aniaml { dog* overrideme(organism* ) override { ... } ↑↑↑ ↑↑↑↑↑↑↑↑ covariant contravariant }; it seems little unintuitive, create sense. if expecting animal*, should able handle animal* (of dog* qualifies). conversely, if doing operation on animal*, need operation can take animal* - , operation takes organism* qualifies on front.
note if input covariant, break type system. consider like;
animal* = new dog; a->overrideme(new cat); if dog::overrideme allowed take dog*, fail - cat* not dog*! allowed take animal* ... or more generic (e.g. organism*), since of work fine.
c++ not have back upwards contravariance in input, covariance in output. write either:
dog* overrideme(animal* ) override { ... } or:
animal* overrideme(animal* ) override { .... } but nil else.
c++ inheritance interface abstract-class pure-virtual
Comments
Post a Comment