Ok guys ! I'm trying to study operator overloading. which i found the toughest article in OOP :(
I tried a code for == operator overloading to check whether both arrays have same elements or not but it isn't working. Can anyone help?
Here is my code:


using namespace std;

class array
        int arr[5];

        for (int i=0;i<5;i++)

        for(int j=0;j<5;j++)

        for(int k=0;k<5;k++)

    int operator ==(array a)
        return 1;
        return 0;

int main()
    array obj1,obj2;
    cout<<"enter five elements in array 1:"<<endl;
    cout<<endl<<"enter five elements in array 2:"<<endl;
    cout<<endl<<"elements in array 1 are: "<<endl;
    cout<<endl<<"elements in array 2 are: "<<endl;

    cout<<"both arrays have same elements"<<endl;
    cout<<"both arrays are different";
    return 0;

Recommended Answers

All 5 Replies


This appears to be an attempt to compare an array of five ints with a custom made class named array. This makes no sense. As an aside, do not name your custom class "array". That's a terrible name, because it will make people (including you) think of it as an array (which it is not) and also because there already is something named array in C++ http://en.cppreference.com/w/cpp/container/array

You need to go back and think about how you can take two objects of your custom class and work out if their internal array have the same values.

It's going to involve looking at each of those values in the internal array and comparing them. Individually. One at a time.

I really didn't get this how to overload comparison operator :/

You may wanna change your class name to say txt or whatever.
Array is a C++ lib. MosChops just warned you aboout that.
Now add change to say class txt and add this code.

   enum {MAX_INT=5};// global enum

  bool operator ==(txt a){
      return a.getSize() == getSize();

    const int getSize(void)const{
        int sum  = 0;
        for (int x=0; x < MAX_INT; x++) {
            sum += arr[x];
        return sum;

I want you to figure things out yourself.

richieking !

thank you, your code worked :)
I figured it out and found helpfull.
Can you tell me about enumeration in simple words you used. I read about it through different resources but didn't get what actually it is?

you need to compare both arrays element by element to check their equality.
in == operator function, first check the size of both arrays, if equal then compare each element of both arrays in loop.

for (int loop=0; loop<size; loop++)

    if (arr1[loop]!= arr2[loop])
        break; // break from the loop , showing both arrays are not equal
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.