以下代码由于使用虚继承而崩溃(访问冲突错误)。
据我所知,虚继承通过强制使用一个类的单个实例来解决钻石问题。在这种情况下,Derived类仅继承了一个IObject类的实例,因此不应该有问题,但是它却崩溃了。
class IObject
{
public:
virtual int getType()=0;
};
class Base : public IObject
{
protected:
int val;
public:
Base() { val = 1; }
virtual int getType();
};
int Base::getType() { return val; }
class Derived : public virtual Base //If I remove the virtual keyword here problem is solved.
{
public:
Derived() { val = 2; }
};
int getVal( void* ptr )
{
return ((IObject*)ptr)->getType();
}
int main()
{
void* ptr = new Derived();
cout << getVal(ptr) << endl;
return 0;
}