Get address of base object from derived object

别等时光非礼了梦想. 提交于 2019-12-04 19:38:23
David Hammen

Going from a pointer to derived class to a pointer to a base class is easy:

Derived * derived_ptr = < some pointer >;
Base * base_ptr = derived_ptr;

If you want to be pedantic, you can use static_cast on the right hand side of the assignment:

Base * base_ptr = static_cast<Base*>(derived_ptr);

Going from a pointer to a base class to a pointer to a derived class uses dynamic_cast:

Derived * derived_ptr = dynamic_cast<Derived*>(base_ptr);

However, this won't always work. You need to have run-time typeid enabled and the base class needs to have at least one virtual method.

Before you go doing this, why do you need to go from a base pointer to a derived pointer? That is a clue that you may need to rethink your design.

There is only one object, it is composed of a Base and a Derived- that is, the Base is put into memory right next to the Derived, in most implementations. That means that the Base* is not the same as Derived* in the general case, but they will be very close.

Now, you can trivially obtain the Base* from the Derived*, the cast is implicit, but you can also make it explicit:

Derived* dptr = ...;
Base* ptr = dptr;

However, there is nothing stopping a single derived object from containing multiple Base objects. Usually this is not the case, but it can happen. That means that you cannot compare Base pointers and expect to know if you are dealing with the same object, only the same Base subobject.

In the simple case of single inheritance, with most compilers:

If you've got a pointer to the derived class, then that's the same as the pointer to the base class. Both pointers have the same value and point to the same memory address.

In memory, if you create an instance of a derived class, it will be laid out as the members of the base object, followed by the members of the derived object. The base class members form part of the derived object.

class Base
{
   int b;
};

class Derived : public Base
{
   int d;
};

In memory, say the Derived pointer is 0400. Then:

0400 byte 1 of b
0401 byte 2 of b
0402 byte 3 of b
0403 byte 4 of b
0404 byte 1 of d
0405 byte 2 of d
0406 byte 3 of d
0407 byte 4 of d

The derived object consists of the base members and derived's own members, and the address of both of these starts at 0400.

It just so happens, that at 0400, the base object part of derived is located. So, base and derived have the same address.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!