Skip to content

All about arrow operator and its Overloading#19

Open
Butcher3Years wants to merge 1 commit intoCopying--Copying-Constructorfrom
Arrow--Operator
Open

All about arrow operator and its Overloading#19
Butcher3Years wants to merge 1 commit intoCopying--Copying-Constructorfrom
Arrow--Operator

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Arrow Operator (->) & Its Overloading – Pointer Sugar + Custom Behavior

The arrow operator (->) is syntactic sugar in C++ for dereferencing a pointer and accessing a member in one go.

Basic Meaning (No Overloading)

Entity* ptr = new Entity(10, 20);

// These are 100% identical:
(*ptr).x = 100;          // dereference first → then dot access
ptr->x = 100;            // arrow = shorthand for (*ptr).x


"Arrow isn't magic — it's literally just (*ptr).member.
The compiler rewrites ptr->x to (*ptr).x behind your back."


"Offset" / Indexing Use Case – Overloading


// Simple array-like class with arrow overload
template<typename T>
class ArrayPtr {
private:
    T* data;

public:
    ArrayPtr(size_t size) : data(new T[size]) {}
    ~ArrayPtr() { delete[] data; }

    // Arrow overload → returns pointer to start
    T* operator->() const { return data; }

    // Index access (offset)
    T& operator<a href="size_t index" target="_blank" rel="noopener noreferrer nofollow"></a> { return data[index]; }
};

int main() {
    ArrayPtr<int> arr(5);
    arr[0] = 100;               // offset/index via []
    arr->x = 200;               // arrow → points to arr[0] if T had x
}





Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant