When I have nested objects, changing the parameter of one object changes the same parameter in others

2 views (last 30 days)
I am working with two handle classes, Class1 and Class2, defined as follows:
classdef Class1 < handle
properties
a = Class2;
end
end
classdef Class2 < handle
    properties
        b = 1;
    end
end
If I create two separate instances of Class1 and adjust the value of parameter 'b' in the nested instance of Class2, the value of 'b' in both instances of Class 1 change. Is this supposed to happen?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 13 Oct 2022
Edited: MathWorks Support Team on 13 Oct 2022
This is an intended behavior for handle classes, and is documented here:
When a constructor for a handle class is placed in the 'properties' section of a class definition, MATLAB creates one generic object of that class and makes the property a handle to that object. If multiple constructors for the same class appear in the 'properties' section, or if multiple objects are created that have the same constructor in their 'properties', a handle to that same generic object are assigned to those properties. In other words, MATLAB does not create a new object every time the constructor is called in the properties section, instead it creates one object and links every constructor call to it.
This behavior can be eliminated by moving the constructor call from the properties section to the constructor of the object. For example, Class1 in the questions can be changed to:
classdef Class1 < handle
    properties
        a;
    end
    methods
        function obj = Class1()
            obj.a = Class2();
        end
    end
end

More Answers (0)

Categories

Find more on Class File Organization in Help Center and File Exchange

Tags

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!