Pointer to Object Questions

Frank Benoit (keinfarbton) benoit at tionex.removethispart.de
Sat Dec 30 14:57:35 PST 2006


I want to add this pitfalls (3) and (5):

interface I {}
class O : I {}
void main(){
  O o = new O;
  O[] oa;
  I[] ia;

  // (1)
  I i1 = o;
  // downcast: This is ok.
  // The compiler does apply a pointer adjustement.

  // (2)
  O o2 = cast(O)i1;
  // upcast: Needs explicit cast. This is ok.
  // The compiler does apply a pointer adjustement.

  // (3)
  void* ptr = cast(void*)o;
  I i2 = cast(I)ptr; // error!
  // The compiler cannot apply the pointer adjustement.
  // will result in undefined behaviour.

  // (4)
  ia.length = oa.length;
  for( int idx = 0; idx < oa.length; idx++ ){
    ia[idx] = oa[idx];
  }
  // and array cannot be casted in one step.
  // this can be done with a templated "arraycast"

  // (5)
  ia = cast(I[])oa;
  // error, this is something like (3). "reinterpret_cast"
  // again undevined behaviour

}



More information about the Digitalmars-d-learn mailing list