Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloading of the plus operator

I want to add 2 objects, by overloading the + operator, but my compiler says there's no matching function to call to point::point(int, int). Can somebody please help me with this code, and explain the error ? thank you

#include <iostream>

using namespace std;

class point{
int x,y;
public:
  point operator+ (point & first, point & second)
    {
        return point (first.x + second.x,first.y + second.y);
    }
};

int main()
{
    point lf (1,3)
    point ls (4,5)
    point el = lf + ls;
    return 0;
}
like image 215
Snowshoot Avatar asked Sep 17 '18 22:09

Snowshoot


People also ask

Can ++ operator be overloaded?

The postfix increment operator ++ can be overloaded for a class type by declaring a nonmember function operator operator++() with two arguments, the first having class type and the second having type int . Alternatively, you can declare a member function operator operator++() with one argument having type int .

What is the overloading in C Plus Plus?

Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.

Why (+) operator is also called an overloaded operator?

Operator Overloading in C++ This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

What are the types of overloading in C Plus Plus?

There are mainly two types of overloading, i.e. function overloading and operator overloading.


1 Answers

You can just change your code like this,

#include <iostream>

using namespace std;

class point {
    int x, y;
public:
    point(int i, int j)
    {
        x = i;
        y = j;
    }

    point operator+ (const point & first) const
    {
        return point(x + first.x, y + first.y);
    }

};

int main()
{
    point lf(1, 3);
    point ls(4, 5);
    point el = lf + ls;

    return 0;
}

Hope this helps...

like image 178
Chathura Dhanuska Avatar answered Oct 21 '22 21:10

Chathura Dhanuska