Home Overload assignment(=) operator in Pair Template
Reply: 1

Overload assignment(=) operator in Pair Template

Devendra Verma
1#
Devendra Verma Published in 2017-12-06 17:56:28Z

This question already has an answer here:

  • What are the basic rules and idioms for operator overloading? 7 answers

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
2#
Vlad from Moscow Reply to 2017-12-06 18:02:59Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.309625 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO