2

I have defined a simple class called MySettings, which internally holds for others settings defined in a class called MySubSettings:

%% --- Definition for MySubSettings
classdef MySubSettings < handle    
    properties
        Fifi = 666;        
    end    
end

%% --- Definition for MySettings
classdef MySettings < handle    
    properties
        Riri = 42; 
        Subs = MySubSettings();
    end   
end

The first time I instantiate MySettings with s = MySettings(); everything is ok (Property Riri is initialized to 42 and Subs is an instance of MySubSettings with property Fifi initialized to 666) ... So far so good ...

Now if I modify property values and reassign s to new instance like this:

s.Riri = 0;
s.Subs.Fifi = 0;
s = MySettings();

Then inspecting new values for properties in new s instance ... I have s.Riri which is equal to 42 (as expected) ... but s.Subs.Fifi is still equal to 0 where I would have expected it to be reinitialized to 666 (???)

Why only Riri is initialized ? Am I doing something wrong or is it a bug ?

Note: I have the issue with R2013b and R2014b.

1
  • welcome to the wonderful world of MATLAB OOP :) Commented Oct 23, 2015 at 10:44

1 Answer 1

3

My misunderstanding ...

Values assigned to properties in class definition are not initial values (like in C# for instance) BUT default values and are no longer re-evaluated after the class is first used.

In my example, as MySubSettings is a handle class, any value assigned to it becomes the new default for next instances.

This default value concept is a bit confusing ... but ok, it was my mistake ... sorry.

Sign up to request clarification or add additional context in comments.

2 Comments

This is correct. To get the behaviour you were expecting, assign the initial value for MySubSettings within the constructor of mySettings, rather than as a default property value. For a criticism of this design of MATLAB OO, see @Yair 's recent article on his UndocumentedMATLAB blog, and for a defence of it see the comments to the article from me and Dave Foti.
@SamRoberts Thanks for these clarifications, I was indeed wondering why to have such 'default value' concept and not just simply 'per instance initialization'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.