Ziyad Mestour
Ziyad Mestour

Reputation: 97

Overload of the operator <<

Why there is no need to define an overload for "<<" having the following situation ?

The class

class T{
    int n ;
    int *pn;
public:
    T(int);
    T(const T&);
    T (int [5]);
    ~T();
    int& operator[] (int);
};

The main

int main()
{
    int tab[5] = {1,2,3,4,5};
    T a = tab;
    for(int i = 0; i < 5; i++)
    cout << a[i] << " ";
    cout << endl;
    T b = a;
    b[1] = 0;
    b[3] = 0;
    for(int i = 0; i < 5; i++)
    cout << b[i] << " ";
    cout << endl;
    return 0;
}

Thanks

Upvotes: 0

Views: 73

Answers (3)

aldo
aldo

Reputation: 2987

You are only sending int to the output stream. The operator

int& T::operator[] (int);

returns an int&, so on the lines

cout << a[i] << " ";

and

cout << b[i] << " ";

you are using the stream's built-in operator for int. No special handling of class T is required, because no instance of T is ever sent to the stream.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

In fact it is impossible to say whether you need to overload the operator or not. Its depends on how you are going to design the class and to use it. The fact that you do not use the operator in your main function does not mean that the class itself does not need the operator. For example as for me then this code

for(int i = 0; i < 5; i++)
cout << a[i] << " ";

is not clear. What is the magic number 5? May I use other numbers in the loop? The fact that some constructor accepts as parameter int[5] says nothing because equivalent parameter definitions can look as int[10], int [], or int *.

So it can not be said surely whether your class need this operator on not.

Classes usually simulate some behaviour or some objects. It is not clear what is the behaviour of your class (whether it is a container or something else) and as the result it is impossible to say whether the operator is needed or not.

Upvotes: 0

user1246792
user1246792

Reputation: 51

In both cases:

cout << a[i] << " ";
cout << b[i] << " ";

T::operator[](int) will be called which returns int&. std::stream defines operator<< for basic types (including int) so no custom operator<< is needed in this case.

You will need to overload the << operator for T in case if you want to output the whole class T, for example

T a(0);
cout << a;

Upvotes: 4

Related Questions