Lesson 14 | Overloading the structure pointer operator |
Objective | Overload -> operator for vector class. |
Overloading Pointer Operator in C++
Overload the -> operator for the vector class so the operator implements an iterator.
The structure pointer operator ->
can be overloaded as a nonstatic class member function. The overloaded structure pointer operator is a unary operator on its left operand.
The argument must be either a class
object or a reference of this type. It can return either a pointer to a class
object or an object of a class
for which the ->
operator is defined.
In the following example we overload the structure pointer operator inside the class t_ptr
. Objects of type t_ptr
act as controlled access pointers to objects of type triple
:
// Overloading the structure pointer operator.
#include <iostream.h>
class triple {
public:
triple(int a, int b, int c) { i = a; j = b; k = c; }
void print() { cout << "\ni = " << i << ", j = "
<< j << ", k = " << k; }
private:
int i, j, k;
};
triple unauthor(0, 0, 0);
class t_ptr {
public:
t_ptr(bool f, triple* p) { access = f; ptr = p; }
triple* operator ->();
private:
bool access;
triple* ptr;
};
triple* t_ptr::operator ->(){
if (access)
return (ptr);
else {
cout << "\nunauthorized access";
return (&unauthor);
}
}
The variable t_ptr::access
is tested by the overloaded operator ->
, and, if true
, access is granted. The following code illustrates this:
void main(){
triple a(1, 2, 3), b(4, 5, 6);
t_ptr ta(false, &a), tb(true, &b);
ta -> print(); //access denied
tb -> print(); //access granted
}
Overload Indirect Member Selection
Click the Exercise link below to overload the -> operator for the
vector class
so the operator implements an iterator.
Overload
Indirect Member Selection