-5

Three classes as below:

class Base
{
public:
    int var1;
};
class Base2
{
public:
    int var2;
};
class Derive:public Base,public Base2
{
public:
    int var3;
};
int main()
{

    printf("%d %d %d %d %d", &Base::var1, &Base2::var2, &Derive::var1, &Derive::var2, &Derive::var3);
    int Derive::* p = &Derive::var1;
    Derive d;
    d.var1 = 2;
    printf("%d", d.*p);
}

The output result is 0 0 0 0 8 2. I am confused about the result of &Derive::var1 and &Derive::var2. Why they are both equal 0 rather than 0 and 4 respectively ?

Note:I test it with gcc4.7.1 and vs2010. And the results are the same.

tenos
  • 909
  • 1
  • 9
  • 16
  • 2
    If you think any of them should be equal to something other than zero, you should consider including _all_ of the relevant code... nothing you've posted includes this. – mah Mar 09 '14 at 14:58
  • For pointing to members you should have at least an instance! – πάντα ῥεῖ Mar 09 '14 at 15:02
  • @πάνταῥεῖ You don't need an instance to get a pointer to a member function just to call it. – Captain Obvlious Mar 09 '14 at 15:02
  • @πάνταῥεῖ I thought this also at the first glance, but please notice that this is valid syntax. `&Foo::a` will return the **offset** to the member – Sebastian Hoffmann Mar 09 '14 at 15:03
  • @Paranaix I was aware of this, and that it's valid syntax! My way of thinking was: Using _real_ member addresses of an instance should give the OP some clarification. – πάντα ῥεῖ Mar 09 '14 at 15:08
  • @mah @πάντα There is no need to binding a instance to the point of class member. As @Paranaix said `&Foo::a` is the offset of variable `a` in the memory of class `Foo`. Anyway some code is appended and it worked as my expectation. – tenos Mar 10 '14 at 08:50
  • possible duplicate of [Address of C++ pointer to class data member in Visual Studio](http://stackoverflow.com/questions/15519855/address-of-c-pointer-to-class-data-member-in-visual-studio) – songyuanyao Mar 10 '14 at 09:40

1 Answers1

0

As @HerbSutter answered in Address of C++ pointer to class data member in Visual Studio,:

The type of &Derive::var1 is int Base::* instead of int Derive::*.

The type of &Derive::var2 is int Base2::* instead of int Derive::*.

Community
  • 1
  • 1
tenos
  • 909
  • 1
  • 9
  • 16