c++11 - C++: inexplicable "pure virtual function call" error -


i having bit of struggle microsoft visual c++ 2015 , able replicate issue small program. given following classes:

class baseclass { public:     baseclass()         : mvalue( 0 )         , mdirty( true )     {}     virtual ~baseclass() {}     virtual int getvalue() const { if( mdirty ) updatevalue(); return mvalue; }  protected:     virtual void updatevalue() const = 0;      mutable bool mdirty;     mutable int  mvalue; };  class derivedclass : public baseclass { public:     derivedclass() {}  protected:     void updatevalue() const override     {         mvalue++;         mdirty = false;     } };  class impersonator { public:     impersonator() {}      // conversion operator     operator derivedclass() const     {         return derivedclass();     }      // conversion method     derivedclass toderived() const     {         return derivedclass();     } }; 

i "pure virtual function call" error when following:

void use( const baseclass &inst ) {     // calls `getvalue` in turns calls virtual function 'updatevalue'     int value = inst.getvalue(); }  int main() {     // creates temporary, passes reference:     use( derivedclass() ); // works      // calls conversion operator create object on stack, passes reference:     derivedclass = impersonator();     use( ); // works      // calls conversion method create temporary, passes reference:     use( impersonator().toderived() ); // works      // calls conversion operator create temporary, passes reference:     impersonator j = impersonator();     use( j ); // causes pure virtual function call error!      return 0; } 

given can't change void use(const baseclass&) function, can change in impersonator class allow using last call without generating debug error?

the way mitigate problem see add operator const baseclass&() impersonator , have return reference derivedclass.

this create better conversion problematic/erroneous 1 compiler trying use.

naturally impersonator won't able return value , create temporary, have own derivedclass object, or many objects, , dispose them somehow @ appropriate time. simplest way works demo program have return reference data member, real program may have else.

class impersonator { public:     impersonator() {}      // conversion operator     operator derivedclass()     {         return d;     }     operator const baseclass&()     {         return d;     }  private:     derivedclass d; }; 

Comments