Returning an object of the same class from an overloaded method operation "plus" rather than struct?

51 views Asked by At

I have a MATLAB class that has a simple overloaded plus function, and I can't get it to return an object. I want the function to add each field value together and output an object of the same class, with the field values being sums of the two inputs. When I add the two objects together, I get a struct, not an object. I am new to classes and am likely doing this wrong; any help would be great.

The code is as follows:

classdef Molar
    properties
        A = 0;
        B = 0;
        C = 0;
    end
    methods
        function M = Molar(val)
           M.A = val;
           M.B = val+1;
           M.C = val+2;
        end
        function M = plus(M1,M2)
            M.A = M1.A + M2.A;
            M.B = M1.B + M2.B;
            M.C = M1.C + M2.C;
        end

    end
end

When it runs and I do:

>> x = Molar(2)
x = 
  Molar with properties:

    A: 2
    B: 3
    C: 4
>> y = Molar(3)
y = 
  Molar with properties:

    A: 3
    B: 4
    C: 5

Then I get a struct when I do the + operation. How can I get this to return another Molar object?

>> x+y
ans = 
  struct with fields:

    A: 5
    B: 7
    C: 9

I wonder if it has to do with needing to use the constructor method differently? Any help in this regard would be appreciated.

1

There are 1 answers

2
rahnema1 On

The first parameter should be the returned value:

function M = plus(M,M2)
    M.A = M.A + M2.A;
    M.B = M.B + M2.B;
    M.C = M.C + M2.C;
end