Unlocking the Power of Pointers in C++

When it comes to programming in C++, understanding pointers is crucial. But did you know that pointers can be created not only for built-in types like integers and floats, but also for user-defined types like structures?

Pointers to Structures: A Deeper Look

Let’s dive into an example where we create a pointer to a structure.

struct Dimension {
    int inch;
    int feet;
};

int main() {
    Dimension d;
    Dimension* ptr = &d; // ptr is pointing to variable d
    (*ptr).inch = 10;
    (*ptr).feet = 5;
    return 0;
}

Key Takeaways

  • (*ptr).inch and d.inch are equivalent.
  • (*ptr).feet and d.feet are equivalent.
  • Remember that the . operator has a higher precedence than the * operator, so we enclose *ptr in brackets when using (*ptr).inch.

The Arrow (->) Operator: A Shortcut to Success

But there’s an even easier way to access member variables and functions of a structure variable through a pointer: the arrow (->) operator.

int main() {
    Dimension d;
    Dimension* ptr = &d; // ptr is pointing to variable d
    ptr->inch = 10;
    ptr->feet = 5;
    return 0;
}

Accessing Member Variables with the Arrow Operator

Here’s an example where we use the arrow operator to access the member variable of variable d.

int main() {
    Dimension d;
    Dimension* ptr = &d; // ptr is pointing to variable d
    cout << ptr->inch << endl; // outputs 10
    cout << ptr->feet << endl; // outputs 5
    return 0;
}

Important Note

(*ptr).inch and ptr->inch are equivalent.

Accessing Member Functions with the Arrow Operator

And it’s not just limited to member variables – we can also use the arrow operator to access member functions of a structure variable through a pointer.

struct Dimension {
    int inch;
    int feet;
    void print() {
        cout << "Inch: " << inch << ", Feet: " << feet << endl;
    }
};

int main() {
    Dimension d;
    Dimension* ptr = &d; // ptr is pointing to variable d
    ptr->print(); // outputs "Inch: 10, Feet: 5"
    return 0;
}

Example Output

In this example, we access the member function of variable d using the pointer.

Inch: 10, Feet: 5

By mastering pointers and the arrow operator, you’ll unlock a new level of efficiency and power in your C++ programming.

Leave a Reply