I am having a bit of a struggle with Microsoft Visual C++ 2015 and was able to replicate the issue with a small program. Given the 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 get a "pure virtual function call" error when I do the following:
void use( const BaseClass &inst )
{
// calls `getValue` which in turns calls the virtual function 'updateValue'
int value = inst.getValue();
}
int main()
{
// creates a temporary, then passes it by reference:
use( DerivedClass() ); // this works
// calls conversion operator to create object on stack, then passes it by reference:
DerivedClass i = Impersonator();
use( i ); // this works
// calls conversion method to create a temporary, then passes it by reference:
use( Impersonator().toDerived() ); // this works
// calls conversion operator to create a temporary, then passes it by reference:
Impersonator j = Impersonator();
use( j ); // causes a pure virtual function call error!
return 0;
}
Given that I can't change the void use(const BaseClass&)
function, can I change anything in the Impersonator
class to allow using the last call without generating a debug error?
getValue
and inspect the vtable pointer, MSVC thinks you have aBaseClass
object, which looks incorrect. – ClubBaseClass::BaseClass
to copy the temporary returned fromoperator DerivedClass
despiteBaseClass
being abstract. Explicit declaration of the copy constructor as non-public makes MSVC complain: error C2248: 'BaseClass::BaseClass' : cannot access protected member declared in class 'BaseClass'. – SanderlinBaseClass
being abstact:Impersonator j = Impersonator(); BaseClass const& k = j; use( k );
– SanderlinDerivedClass
object produces the expected code; copy constructor is omitted entirely. – SanderlinBaseClass::updateValue
non-pure and feed the program to the old gcc,BaseClass::updateValue
gets called. It looks like the old gcc and the new MSVC somehow share a bug. – CheckreinImpersonator
to create aDerivedClass
, instead of a conversion operator, it works:DerivedClass toDerived() const { return DerivedClass(); }
. I'll add this to the sample code. – Leonieprotected: BaseClass(const BaseClass& r) { throw 1; }
compilation fails on that line witherror C2248: 'BaseClass::BaseClass': cannot access protected member
– Bruis