Constructor behaviour in Classes

조회 수: 11 (최근 30일)
Sles
Sles 2017년 9월 27일
답변: Guillaume 2017년 9월 27일
Main Question: Is this normal behaviour?
I've encountered some strange behaviour when initilizing properties of classes (child of handle):
Note: example test-script in zip-file (attachement)
classdef pokemon< handle % baseClass
%POKEMON container
% dummy example
properties
moves = Moves() ; %Moves is also a (custom) class (child from handle)
level;
end
methods
function obj = pokemon(obj)
% obj.moves = Moves(); % if the property is initialized here, it
% works likes excepted.
end
function getname(obj)
% does nothing
end
end
end
When a property is initilized in the 'properties' section:
A= Pokemon; B = Pokemon;
The handle of A.moves and B.moves is the same. ( change A.moves, B.moves also changes)
If the property is initilized in the constructor (like I would normaly do), A.moves and B.moves are two different objects.
Sub-Question: Why does it behaves differently?

채택된 답변

Guillaume
Guillaume 2017년 9월 27일
This is normal behaviour and 'documented' (but extremely hard to find in the doc even when you what you're looking for!)
Basically, all initialisations in a property section is done only once, when the class is loaded (i.e first use). After that the initialisation value is shared by all instances. It only matters when the initialised property is a handle class, and indeed for these you must initialise the property in the constructor.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by