0

I have the following snippet of code:

class Base {
//...
};

class Subclass : public Base {
public:
    void foo() {
        Base& ref = (*this);
    }
//...
};

Where I pass this reference to the constructor of some other objects for later use. According to the following article (and what I know about references), if I get the address of ref, it should be the same as this.

Is the address of a reference to a dereferenced pointer the same as the address of the pointer?

However, this is what I am seeing when I run the code:

this    0x20002288 
&ref    0x20003314

The addresses are NOT the same. Does anyone know why this would be?

Thanks!

Patrick Wright
  • 1,401
  • 7
  • 13
  • Reference are _sometimes_ just different names for the same object, and _sometimes_ they are an actual object that passes through all usages to the referred object. :( – Mooing Duck Mar 11 '21 at 19:44
  • The way you set this up in the question makes me think that there's more to it. Please make a [mre]. You can build on [this](https://godbolt.org/z/5an799) if you'd like. – Ted Lyngmo Mar 11 '21 at 19:49
  • @MooingDuck Could you elaborate on this a bit more? If my reference is not just a different name for 'this', then what is it referring to exactly? The subclass itself? – Patrick Wright Mar 11 '21 at 19:49
  • 3
    I mean, you're bringing inheritance into the mix, maybe vtables. You don't show enough code. Like how you're even getting your output. – sweenish Mar 11 '21 at 19:51
  • @TedLyngmo Just by you saying that, I wonder if my problem is due to the fact that the real class I am testing with is using multiple inheritance... – Patrick Wright Mar 11 '21 at 19:55
  • Minimal example: https://gcc.godbolt.org/z/rTznTv – chris Mar 11 '21 at 20:04

1 Answers1

2

I found the source of the problem, and it has to do with multiple inheritance. Here is a simplified example:

#include <stdio.h>

class Base1 {
private:
    int _a;
    int _b;
};

class Base2 {
public:
    ~Base2() {
        
    }
    
    virtual void* foo() = 0;
    
private:
    int _x;
};

class Child : public Base1, public Base2 {
public:
    void* foo() override {
        Base1& baseRef = (*this);
        return static_cast<void*>(&baseRef);
    }

private:
    int _c;
};

int main() {
    Child c;

    printf("&c=%p\r\n",&c);
    printf("c.foo()=%p\r\n",c.foo());
    
    Base2* c2 = new Child;
    
    printf("c2=%p\r\n",c2);
    printf("c2->foo()=%p\r\n",c2->foo());

    return 0;
}

Where the output is:

&c=000000000061FDF0
c.foo()=000000000061FDFC
c2=00000000007034A0
c2->foo()=00000000007034AC
Patrick Wright
  • 1,401
  • 7
  • 13