Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading Addition (+) operator for own classes/objects

I created a class xyz which results in a matrix comprising only integers. If I try to add two instances of that class, I do receive the error message:

"Undefined operator '+' for input arguments of type 'xyz'."

What am I supposed to do to make the in-built + operator compatible with instances of my class?

like image 344
Andi Avatar asked Jul 26 '26 17:07

Andi


1 Answers

You have to use the plus method to override the behavior of +

classdef MyObject

    properties
        value
    end

    methods
        function this = MyObject(v)
            this.value = v;
        end

        function result = plus(this, that)
            % Create a new object by adding the value property of the two objects
            result = MyObject(this.value + that.value);
        end
    end
end

Then use it like:

one = MyObject(1)
%  MyObject with properties:
%
%   value: 1


two = MyObject(2)
%  MyObject with properties:
%
%   value: 2

three = one + two
%  MyObject with properties:
%
%   value: 3

For other common operators, there is an extensive list here

like image 92
Suever Avatar answered Jul 28 '26 08:07

Suever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!