Reputation: 71
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?
Upvotes: 0
Views: 56
Reputation: 736
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:
(Rectangle*)
, this is why we have parentheses in ((Rectangle*)p1->r1)
.Upvotes: 3