-1
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?

Naveen
  • 74,600
  • 47
  • 176
  • 233
kam
  • 261
  • 1
  • 3
  • 7
  • 4
    there is no object slicing here. Can you be more specific? what is meant by *accessing* object slicing? – Naveen May 07 '10 at 10:01
  • 1
    Please see http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c for a good discussion on this – Robben_Ford_Fan_boy May 07 '10 at 10:02
  • @Naveen: But unless you, as a programmer keep of track, remembering that it is a B, there is no way to know that `*a` also contains a B part, so it is as good as sliced. – UncleBens May 07 '10 at 14:01
  • Instead of recommending it to be closed (as not a question) why not help OP fix the terminology, because the intent of the question seems quite obvious (how to access members in a derived class through a pointer to base class?) – UncleBens May 07 '10 at 14:16

2 Answers2

1

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.

wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
0

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.

UncleBens
  • 40,819
  • 6
  • 57
  • 90