Reputation: 171
I have a very interesting observation that may or may not be expected. I have two very complicated classes that each extend many other unrelated classes. For reference, one is a socket and one is a virtual device. During construction of the virtual device, I want to pass the address of the device to the a socket object. The socket object is also part of the virtual device. It basically looks like this
class TcpSocket : public Socket, public OtherThing {
void Init(OtherOtherClass *device){
printf("0x%x\n", device); //0x1aaaf794
}
};
class Device : public OtherClass, public OtherOtherClass {
Device(){
printf("0x%x\n", this); //0x1aaaf6d0
this->socket.Init(this);
printf("0x%x\n", this); //0x1aaaf6d0
}
TcpSocket socket;
};
I cannot reproduce this in a sandbox environment, but when I print out the addresses, they are different. So maybe I will just ask the question.
In function TcpSocket::Init
it is expecting an OtherOtherClass*
and not a Device*
. Is this the reason why the address appears to be different?
Upvotes: 2
Views: 88
Reputation: 596417
Class Inheritance is an "is-a" relationship. Device
contains everything that is in OtherClass
, and everything is that in OtherOtherClass
. So, a Device
object is also an OtherClass
object, and is also an OtherOtherClass
object.
When you have a Device*
pointer (or Device&
reference) to a Device
object, it points/refers to the Device
portion of the object. And when you have an OtherOtherClass*
pointer (or OtherOtherClass&
reference) to a Device
object, it points/refers to the OtherOtherClass
portion of the object. And the same with OtherClass
.
That is why you see a different memory address being reported in TcpSocket::Init()
than you do in Device::Device()
. You have two pointers to different portions of the same object.
Upvotes: 3
Reputation: 908
Yes.
Device
has several base classes. When converting a Device*
pointer to a OtherOtherClass*
pointer, the value will be different since the new pointer will be pointing at the instance of OtherOtherClass
within the instance of Device
.
Upvotes: 4