开发者

How to access object slicing?

class A
{
public:开发者_如何学运维
int i;
int j;

};

class B : public A
{
public:
int k;

};

main()
{
  A *a = new B;

}

is it possible to access slicing data?


Slicing looks like this:

struct B {
    virtual ~B() { }
};
struct D : public B {
    int a, b;
};

int main()
{
    D der;
    B bas(der);  // der is sliced!
}

There is no way for the B bas object to see the extra information of D der even though the information is there. We say that that extra information got "sliced off". bas can't access any of it because the standard allows D objects to be stored in memory (almost) arbitrarily, for alignment purposes. The only guarantee you have for der is that its first data member's address is the same as the object's address.


I believe the answer is to down-cast the pointer.

static_cast<B*>(a)->k = 10;

The premise is that you actually know for sure that at this point in code a always refers to an instance of B, because, for the lack of virtual functions and a vtable, there is no way for the language to test at run-time, if that cast is valid or not.


Technically, nothing is sliced yet, you just can't access it otherwise because for all the compiler knows, you have a pointer to an object of type A, and this is a case where you simply must know better.


IMO, if you only use inheritance to add data fields to a class that is there only to hold data, you shouldn't generally be messing with pointers to a base class at all.

If you are showing only part of the code and you do have virtual functions in there, use dynamic_cast instead, because then it is possible to check if the cast is valid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜