Classes within classes: How to instantiate object without having its inner class object share memory?

11 views (last 30 days)
SUMMARY : the 'main_class' contains two properties, 1) a single variable property 'x', and 2) a class property 'table_class', which contains only a single property value 'r'.
PROBLEM : Any object instances of the class 'main_class' will have independent values for the 'x' property (each has its own 'x' value), but continues to share the information/memory corresponding to the 'table_class' property (each instance has the same 'table_class' information).
EXAMPLE : 'a' is created as an instance of the 'main_class' and has the values [1 1 1] set to be the 'table' value. Then 'b' is created similarly except that the 'table' value is set to [2 2 2]. Now going back and checking the 'table' value for 'a' we see that it has also been changed to [2 2 2] which is undesired.
How do I keep inner class information separated on a instance-by-instance case?
*main.m***
a = main_class([1 1 1]);
b = main_class([2 2 2]);
a.table.r
*main_class.m***
classdef main_class < handle
properties
x % one variable property
table = table_class(); % one class property
end
methods
function obj = main_class(N)
obj.table.init_table(N);
end
end
end
*table_class.m***
classdef table_class < handle
properties
r = [];
end
methods
function obj = init_table(obj, N)
obj.r = N;
end
end
end
  1 Comment
Adam
Adam on 18 Mar 2015
I was caught by this more than once in my earlier days with OOP. Nowadays I do what Guillaume suggests below.
I tend to initialise my properties block as:
properties
x;
table = table_class.empty;
end
but that is entirely personal preference more as documentation for me than any real programming purpose as the default initialisation is to [] which amounts to the same thing as table_class.empty when you subsequently initialise it properly anyway.
I just like to see at a glance in my properties block what type my properties are if they are to be objects of some other class.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 18 Mar 2015
See When matlab evaluates expressions in class definitions for the explanation of the behaviour you observe. In particular "After initialization, the values returned by these expressions are part of the class definition and are constant for all instances of the class. Each instance of the class uses the results of the initial evaluation of the expressions without reevaluation."
The workaround is simple, do not initialise table in the class definition but do it in the constructor:
classdef main_class < handle
properties
x;
table; %not initialised here
end
methods
function this = main_class(N)
this.table = table_class(); %initialised here
this.table.init_table(N);
end
end
end

More Answers (0)

Categories

Find more on Software Development Tools 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!