use*_*015 9 c++ virtual-inheritance
我们都知道,在使用简单单继承时,派生类的地址与基类的地址相同。多重继承使这一点变得不真实。
虚拟继承是否也使这不真实?换句话说,以下代码是否正确:
struct A {};
struct B : virtual A
{
int i;
};
int main()
{
A* a = new B; // implicit upcast
B* b = reinterpret_cast<B*>(a); // fishy?
b->i = 0;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我们都知道,在使用简单单继承时,派生类的地址与基类的地址相同。
我认为这种说法是不正确的。在下面的代码中,我们有一个简单的(非虚拟的)单(非多重)继承,但地址不同。
class A
{
public:
int getX()
{
return 0;
}
};
class B : public A
{
public:
virtual int getY()
{
return 0;
}
};
int main()
{
B b;
B* pB = &b;
A* pA = static_cast<A*>(pB);
std::cout << "The address of pA is: " << pA << std::endl;
std::cout << "The address of pB is: " << pB << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
VS2015 的输出是:
The address of pA is: 006FF8F0
The address of pB is: 006FF8EC
Run Code Online (Sandbox Code Playgroud)
虚拟继承是否也使这不真实?
如果将上面代码中的继承改为virtual,结果也是一样的。因此,即使在虚拟继承的情况下,基对象和派生对象的地址也可能不同。