-3

Hello everyone I am trying to implement a pair like Template. I have tried this:

#include<iostream>
using namespace std;
template<class T1, class T2>
class Pair
{
    //defining two points
    public:
    T1 first;
    T2 second;

    //default constructor
    Pair():first(T1()), second(T2())
    {}

    //parametrized constructor
    Pair(T1 f, T2 s) : first(f),second(s)
    {}

    //copy constructor
    Pair(const Pair<T1,T2>& otherPair) : first(otherPair.first), second(otherPair.second)
    {}

    //overloading == operator
    bool operator == (const Pair<T1, T2>& otherPair) const
    {
        return (first == otherPair.first) && (second == otherPair.second);
    }

    //overloading = operator
    Pair<T1, T2> operator = (const Pair<T1, T2>& otherPair) 
    {
        first=otherPair.first;
        second=otherPair.second;
        return this;
    }


    int main()
    {
        Pair<int, int> p1(10,20);
        Pair<int, int> p2;
        p2 = p1;
    }

But I am getting the error in the last line of the overloaded method =. It is not allowing to return the this object.

Can anyone help where i am doing wrong?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Devendra Verma
  • 975
  • 2
  • 10
  • 24

1 Answers1

2

The operator should look like

//overloading = operator
Pair<T1, T2> & operator = (const Pair<T1, T2>& otherPair) 
{
    if ( this != &otherPair )
    {
        first=otherPair.first;
        second=otherPair.second;
    }

    return *this;
}

As for the error then you are trying to convert the pointer this to an object of the type Pair in the operator.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • why you are returning *this instead of this? and also changed the return type from Pair to Pair&/. – Devendra Verma Dec 06 '17 at 18:02
  • 1
    @DevendraVerma this has type Pair * while the return type is Pair. There is no implicit conversion from the pointer to an object of the type Pair. In C++ the assignment operator returns reference to lvalue for fundamental types. So a user-defined class should follow this convention. – Vlad from Moscow Dec 06 '17 at 18:04
  • Oh I got this. I was not clear about basics of operator overloading. – Devendra Verma Dec 06 '17 at 18:09