Thread Subject: OOP: add method for object

Subject: OOP: add method for object

From: Sebastian Hölz

Date: 12 Jan, 2012 10:16:08

Message: 1 of 2

I have a handle class with an add-method to extend existing object:

classdef Obj_A < hgsetget
% some props and constructor, which handles nargin==0
  methods
    function obj = add(obj)
      % Some input parsing
      obj(end+1) = MyObj
    end
  end
end

Now I can do the following:
>> obj = Obj_A;
>> obj = obj.add; % obj is now 2x1

What I would like to achive is the following:
>> obj = Obj_A;
>> obj.add; % This does not work, since obj is not updated.

Is this possible?

The reason why I ask is the following: in the class-system I'm currently designing "Obj_A" is actually a property of object "Obj_B":

classdef Obj_B
  property
    Obj_A
  end
end

It would be very convenient (and easier for users) to write:
>> MyObj = Obj_B;
>> MyObj.Obj_A.add;

Instead of
>> MyObj = Obj_B;
>> MyObj.Obj_A = MyObj.Obj_A.add;

OK, I hope I got my point across.

Cheers

Sebastian

Subject: OOP: add method for object

From: Matt J

Date: 14 Jan, 2012 10:59:09

Message: 2 of 2

"Sebastian Hölz" wrote in message <jembt8$1f3$1@newscl01ah.mathworks.com>...
> I have a handle class with an add-method to extend existing object:
>
> classdef Obj_A < hgsetget
> % some props and constructor, which handles nargin==0
> methods
> function obj = add(obj)
> % Some input parsing
> obj(end+1) = MyObj
================

A few preliminary questions. First, how does MyObj get into the workspace of the add method? You have passed only obj... Did you mean the following?

  obj(end+1) = obj

Or did you mean to have the calling signature to be this:

  function add(obj,MyObj)

If the latter, I don't see why you don't just use the default cat operations, e.g.,

obj=[obj,MyObj]


In any case, what you're seeing is still somewhat surprising, and I haven't quite figured out what's going on. Because this is a handle class, I would expect the behavior that you're looking to already be there, although note that there is no need to return a copy of "obj" from a handle method. In other words, if you write the function signature this way

 function add(obj,...)

that should have been sufficient.
 

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
copy on write Matt J 14 Jan, 2012 05:48:47
obscure behavior Matt J 14 Jan, 2012 05:48:47
handle vs value Matt J 14 Jan, 2012 05:48:47
oop Sebastian Hölz 12 Jan, 2012 05:19:12
rssFeed for this Thread

Contact us at files@mathworks.com