1struct car {
2 int year
3 int vin;
4}
5
6struct car myCar;
7p_myCar = &myCar;
8
9myCar.year = 1995;
10// '->' allows you to use the '.' with pointers
11p_myCar->vin = 1234567;
1/*
2 the arrow operator is used for accessing members (fields or methods)
3 of a class or struct
4
5 it dereferences the type, and then performs an element selection (dot) operation
6*/
7
8#include <iostream>
9using std::cout;
10
11class Entity {
12public:
13 const char* name = nullptr;
14private:
15 int x, y;
16public:
17 Entity(int x, int y, const char* name)
18 : x(x), y(y), name(name) {
19 printEntityPosition(this); // "this" just means a pointer to the current Entity
20 }
21
22 int getX() { return x; }
23 int getY() { return y; }
24
25 friend void printEntityPosition(Entity* e);
26
27};
28
29// accessing methods using arrow
30void printEntityPosition(Entity* e) {
31 cout << "Position: " << e->getX() << ", " << e->getY() << "\n";
32}
33
34int main() {
35 /* ----- ARROW ----- */
36
37 Entity* pointer = new Entity(1, 1, "Fred");
38 //printEntityPosition(pointer); redacted for redundancy (say that 5 times fast)
39
40 cout << (*pointer).name << "\n"; // behind the scenes
41 cout << pointer->name << "\n"; // print the name (with an arrow)
42
43 /* ----- NOT ARROW ----- */
44
45 Entity not_a_pointer(2, 2, "Derf");
46 //printEntityPosition(¬_a_pointer); & to convert to pointer
47
48 cout << not_a_pointer.name << "\n"; // print the name (with a dot)
49
50 /* ----- LITERALLY NEITHER ----- */
51
52 std::cin.get(); // wait for input
53 return 0; // exit program
54}
55
56