K
Kush
Hello All,
Once again another question.
This time I would like to understand why one needs to overload the [ ]
operator to access objects in array format?
Example code:
class A {
{ };
class B {
private:
A array[10];
A* pA = array;
public:
A& operator [ ] (int i) { return pA; } //Line 1:
void do_something(void) {
A a;
a = pA[2]; } //Line 2
};
Why do I need Line 1? Since pA is a pointer of type A, can I not
directly access "array members" using simple pointer arithmetic?
i.e. without declaring Line 1, use Line 2
or equivalently use the below statement to replace Line 2
a = *(pA + 2);
I'm sure I'm missing something. Can someone please point out my
misconception?
Thanks again in advance!
Kush
Once again another question.
This time I would like to understand why one needs to overload the [ ]
operator to access objects in array format?
Example code:
class A {
{ };
class B {
private:
A array[10];
A* pA = array;
public:
A& operator [ ] (int i) { return pA; } //Line 1:
void do_something(void) {
A a;
a = pA[2]; } //Line 2
};
Why do I need Line 1? Since pA is a pointer of type A, can I not
directly access "array members" using simple pointer arithmetic?
i.e. without declaring Line 1, use Line 2
or equivalently use the below statement to replace Line 2
a = *(pA + 2);
I'm sure I'm missing something. Can someone please point out my
misconception?
Thanks again in advance!
Kush