Initialization of class instance properties
Show older comments
It seems like Matlab initializes the properties of each instance of a class to the same, single value rather than evaluating the initialization expression for each instance. Why is this? It leads to very unexpected behavior from my perspective:
This works as expected in all cases:
classdef OK < handle
properties (Access=private)
mymap
end
methods
function this = OK()
this.mymap = containers.Map();
end
function add(this, key)
this.mymap(key) = true;
end
function keylist = keys(this)
keylist = this.mymap.keys;
end
end
end
The following class has crazy behavior in 2012b:
classdef WTF < handle
properties (Access=private)
mymap = containers.Map();
end
methods
function add(this, key)
this.mymap(key) = true;
end
function keylist = keys(this)
keylist = this.mymap.keys;
end
end
end
Try these commands:
x = WTF;
y = WTF;
x.keys
>> Empty cell array: 1-by-0
y.keys
>> Empty cell array: 1-by-0
x.add('foobar');
y.keys
>> 'asdf'
Huh? How did y magically get access to x's mymap? Basically, why does Matlab evaluate its property initialization expressions only once ever rather than once per instance?
Accepted Answer
More Answers (0)
Categories
Find more on Work with Components in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!