Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab class constructor calling a method for initialization

In a class constructor, if I call another method to initialize some property, why that property not changed?

Example code:

classdef Test
    properties
        prop    
    end 

    methods
        function obj = Test()
            obj.init(); 
        end     
        function init(obj)
            obj.prop = 1;
        end     
    end 
end

Then by executing A = Test(); I got A.prop = [].

like image 895
Da Kuang Avatar asked May 25 '26 03:05

Da Kuang


1 Answers

Handle class

classdef Test < handle

This will apply methods to the referenced object.

Value class

You have to return the modified object:

function obj = Test()
    obj.init();
end

should be

function obj = Test()
    obj = obj.init();
end

However, your init() is also not returning the modified object to the caller:

function init(obj)
    obj.prop = 1;
end

which should be

function obj = init(obj)
    obj.prop = 1;
end

See also comparing handle and value classes.

like image 199
Oleg Avatar answered May 26 '26 21:05

Oleg