Question

Suppose I have the following 2 classes. How do I use type conversion to achieve an effect as described below? What I want is: I'm returning this + 1 and this - 1 because my 2 classes are always contiguous in memory.

right *r = new right ();
left* l = (left*)r;

class left : public top {
    int b;

    operator right * () {
        return this + 1;
    }
};

class right : public top {
    int c;

    operator left * () {
        return this - 1;
    }
};
Was it helpful?

Solution

There is no safe way to convert an pointer of type right* to a pointer of type left* or vice-versa. You must do one of two things:

  1. Use a pointer of type top* instead. It is safe to convert either a left* or a right* to a top*.
  2. Use a template to perform whatever operation you want to perform on either a left* or a right* (assuming they "look similar" enough that the template code will work on either one).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top