0

I have the following elements.

p1: A pointer to the class union.

r1 A pointer inside the class union which points to a Region Class.

A.x A point inside the class Rectangle.

Union and Rectangle are derived classes from the base class Region.

I'm doing the following operation.

auto p1 = new Union();
p1->r1 = new Rectangle();

Now I want to change a point inside r1.

How can I typecast a pointer inside a pointer, For example I tried this and it doesn't work.

p1->(Rectangle*)r1->B.x = 6;

However this works perfectly,

auto r11 = (Rectangle*)p1->r1;
r11->A.x = 1;

How can I change p1->(Rectangle*)r1->B.x = 6; to directly change A.x without creating a new pointer?

1 Answer 1

3

You need to check out operator precedence and it's associativity. https://en.cppreference.com/w/cpp/language/operator_precedence

The correct form is:

((Rectangle*)p1->r1)->B.x = 6;

To be more precise, this is how it works:

  1. Access Rectangle * member r1 with -> (left-to-right)
  2. Cast it to Rectangle * (right-to-left)
  3. Access B member (left-to-right). Take into account that -> has higher precedence than casting (Rectangle*), this is why we have parentheses in ((Rectangle*)p1->r1).
  4. Access x member through . operator
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.