Hi!
First time poster.
I'm having trouble understanding how nested handle classes work. As far as I've understood handle objects are basically passed as reference, ie copies of an object copies the pointer to the original.
So I created this small sample and did not get what expected.
primaryclass.m
classdef primaryClass < handle properties x myContainedClass = secondaryClass(); endend
SecondaryClass.m
classdef secondaryClass < handle properties y endend
and a small script to present my problem:
a = primaryClass();b = primaryClass();a == b %returns false, as expected since handle objects are created separately.
a.myContainedClass == b.myContainedClass %Returns true, wait what?
As you can see the nested handle class are all pointers to the same object, which is not what I expected.
Im using a very large 3d matrix with custom handle objects that would benefit a lot from having nested unique handle object: inside every primaryClass object resides a unique secondaryClass object, unique to that particular primaryClass object instant.
What am I not understanding and missing?
Thanks for any help!
kind regards Robert Hedman
UPDATE
It seems that this fixes my problem, sometimes….
classdef primaryClass < handle properties x myContainedClass end methods function obj = primaryClass() obj.myContainedClass = secondaryClass(); end endend
This fix makes sense since instantiating a variable within a constructor links the variable to that specific instance of that host object. Instantiating it outside apparently makes the variable a static variable for the entire class.
This does not appear to always work though, see below.
A(2,2,2) = primaryClass();A(1,1,1).myContainedClass == A(2,2,2).myContainedClass %outputs false as expected
bigA(100,100,100) = primaryClass();bigA(1,1,1).myContainedClass == bigA(2,2,2).myContainedClass %outputs true for some wierd reason...
Why is this? How do I get it to function as I expect?
kind regards Robert Hedman
Best Answer