How to handle the error "The 'A' class definition uses an instance of itself directly or indirectly as the default value for the 'b' property. This is not allowed."?

I got an error:
The 'A' class definition uses an instance of itself directly or indirectly as the default value for the 'b' property. This is not allowed.
Below is my code:
classdef A
properties
b = B;
end
end
classdef B
properties
a = A;
end
end
What is wrong in the code? How should I resolve this error?

 Accepted Answer

Cause of the error:
This error is due to recursive property definition. It occurs occurs when a MATLAB class sets a property’s default value to an instance of itself, either directly or indirectly (for example, through another class). This creates an infinite loop when MATLAB tries to initialize the property, so the error is thrown to prevent it. 
In the code example, creating an "A" object needs to create a "B" object as the default value of the property "b". However, when initializing "B"'s property 'a', it requires to create an "A" object as the default value. This leads to infinite recursion.
How to fix:
Use [] (empty array) as the default value for properties that reference other objects. If you need to assign an object to the property, do so explicitly in the class constructor instead of as a property default value.
For example, you can modify the class "A" and "B" as follows: 
classdef A
properties
b = []; % Empty by default
end
methods
function obj = A(bObj)
if nargin > 0
obj.b = bObj;
end
end
end
end
classdef B
properties
a = []; % Empty by default
end
methods
function obj = B(aObj)
if nargin > 0
obj.a = aObj;
end
end
end
end
Then, when you run 
b = B(); % Create B object
a = A(b); % Create A object with b as property
b.a = a; % Set B's a property to the A object
it should run without any error. 
General recommendation:
  1. Review the class you are using as the default value, as well as its superclasses, to check if any of them reference the original class (directly or indirectly) as a property default. 
  2. Use "clear classes" after editing a class file to clear the cached classes.

More Answers (0)

Categories

Products

Release

R2023b

Community Treasure Hunt

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

Start Hunting!