Is double arrow operator a thing in C++?

Viewed 3290
1   #include "Cube.h"
2   using cs225::Cube;
3 
4   int main() {
5   Cube *c1 = new Cube();
6   Cube *c2 = c1;
7   c2->setLength( 10 );
8   return 0;
9   }

This is the code I am working with, is there anything wrong with it? Does line 7 correctly assign the length of 10 to the cube object, or will it return a compiler error. Because my understanding is that the arrow operator will point c2 to c1, but c1 is still a pointer so shouldn't there needs to be ->-> in order to reach the cube object that contains the functions?

2 Answers
Cube *c2 = c1;

This does not point c2 to c1, that would be done by the first line below, with the second line showing how to use it (it's not done with the mythical ->-> operator):

Cube **c2 = &c1;
(*c2)->setLength(10);

The original assignment takes the value of c1 (a pointer to the Cube you allocated) and puts that value into c2. Hence both c1 and c2 now point at the same Cube object.

This is just like:

int answer = 42;
int otherAnswer = answer;

in that it sets otherAnswer to 42, it doesn't make it point to answer. The fact that the original code involves pointers does not change this particular aspect.

c2 is initialized directly with the value of c1 the pointer. So c1 == c2. c2 is not a double pointer Cube **. You can essentially use c2 as you would use c1.

Remember not to use c2 after running delete c1, however.

Related