Object oriented programming - Constructor behavior

조회 수: 1 (최근 30일)
broken_arrow
broken_arrow 2020년 7월 29일
댓글: broken_arrow 2021년 4월 7일
Hello guys,
I'm struggling to understand the behavior of constructor functions. Take the app designer as an example: "app" is the output variable of the constructor (i. e. the object that is created). Yet it is treated like a known (input) variable within the constructor although it is never defined. To my knowledge, this is not possible with all other functions where the return variable is unknown at the start and must be defined within the function. Hence my question: Why does that not apply to the constructor?
% App creation and deletion
methods (Access = public)
% Construct app
function app = XYZapp
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.XYZappUIFigure)
if nargout == 0
clear app
end
end
% more code...
end

채택된 답변

Steven Lord
Steven Lord 2021년 4월 7일
Because class constructors are special. MATLAB knows exactly which method in a class is the class constructor (it has to have the same name as the class) and if the class constructor returns an output the first output must be an instance of the class. See the "Guidelines for Constructors" section on that documentation page.
Also from the "Initializing Objects in Constructor" section on that page: "The output argument is created when the constructor executes, before executing the first line of code."
  댓글 수: 1
broken_arrow
broken_arrow 2021년 4월 7일
Ok, so the constructor indeed is a special function as i suspected. Thanks.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by