blank_manash
blank_manash

Reputation: 71

Type Casting of Pointers to Pointers

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

Answers (1)

Nabuchodonozor
Nabuchodonozor

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:

  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

Upvotes: 3

Related Questions