Re: Why the output for this small pgm so?
nas wrote:
Consider this example program which i hav taken from some site
#include <iostream>
using namespace std;
class Base1 {
public:
virtual void f() { }
};
class Base2 {
public:
virtual void f() { }
};
class Base3 {
public:
virtual void f() { }
};
class Drive : public Base1, public Base2, public Base3 {
};
// any non zero value because multiply zero with any no is zero
#define SOME_VALUE 1
int main() {
cout << (DWORD)static_cast<Base1*>((Drive*)SOME_VALUE)-SOME_VALUE;
cout << (DWORD)static_cast<Base2*>((Drive*)SOME_VALUE)-SOME_VALUE;
cout << (DWORD)static_cast<Base3*>((Drive*)SOME_VALUE)-SOME_VALUE;
return 0;
}
Output of this prgram is:
048
Stuart Redmann wrote:
Seehttp://www.phpcompiler.org/doc/virtualinheritance.htmlfor a good
explanation of these compiler specific implementation details (I know no C++
compiler that uses an implementation that really differs at more than minor
pointers from the design explained there).
nas wrote:
But the initially how we got 0,4,8 ??? What might be the reson for
this?
Let's take a closer look: If you cast the (integer) value 1 to a Drive* pointer,
the compiler will not change the value but change the type attached to this
value (this means that you now have a Drive* pointer pointing to the memory
location 0x00000001). The memory layout of a Drive object (located at memory
address 1) would like the following scheme:
1 5 9 13 (memory addresses)
_______________________________________________________
| Base1 (4 Bytes) | Base2 (4 Bytes) | Base3 (4 Bytes) |
-------------------------------------------------------
| ' = ptr to VMT ' = ptr to VMT '
| of Base2 of Base3 (4 Bytes)
| + members + members (0 Bytes)
L--: ptr to vtable of Drive (this vtable can be used as VMT for both
Base1 and Drive).
Now if you upcast a pointer to Drive to Base1, the compiler doesn't need to
change the address, as the internal Base1 object inside Drive's memory layout
lays at the internal offset zero. The internal Base2 object has offset 4, so
you'll get the address 5 for the Base2 object.
I hope this makes it a bit clearer for you.
Regards,
Stuart