I am calling a function to change parameters of my class inside its constructor, however, I can't change the values. Is this a bug or on purpose?
In the following example, I am calling function "calculateCalculatedProperties()" inside constructor. "calculateCalculatedProperties()" calls "Velocity()" and "Length()" function which sets new values of velocity and length properties. However, at the end product of the constructor (object instance) properties are unchanged.
classdef piping
%PIPING Summary of this class goes here
% Detailed explanation goes here
properties
flowRate
diameter
startLocation location
endLocation location
end
methods
function self = piping(flowRate, diameter, startLocation, endLocation)
self.flowRate = flowRate;
self.diameter = diameter;
self.startLocation = startLocation;
self.endLocation = endLocation;
self.calculateCalculatedProperties();
end
function self = calculateCalculatedProperties(self)
fprintf("hey")
self.Velocity();
self.Length();
end
function self = Velocity(self)
self.velocity = self.flowRate / (pi * self.diameter^2 / 4);
end
function self = Length(self)
self.length = location.calculateDistance(self.startLocation,self.endLocation) ;
fprintf("hey this is lengthhhh")
self.flowRate = 10000000;
end
end
properties % Calculated properties
velocity
length
end
end
The issue here is that you are using a value class, not a handle class. Note that in your Velocity method you are returning an instance of "self", in a value class these method invocations return a separate object, which is being ignored in this code.
That being said two possible solutions:
Capture output of value objects and return the final, modified object.
function self = piping(flowRate, diameter, startLocation, endLocation)
% ...
self = self.calculateCalculatedProperties();
end
function self = calculateCalculatedProperties(self)
fprintf("hey")
self = self.Velocity();
self = self.Length();
end
Use handle classes to create a mutable object.
classdef piping < handle
% ...
end
See Comparison of Handle and Value Classes for more info.