OOP: Object gone out of scope!

4 views (last 30 days)
Ahmed Hossam
Ahmed Hossam on 12 May 2017
Commented: Ahmed Hossam on 12 May 2017
Hi,
I have two handle classes.
In one of them I call the constructor of the other handle class many times.
Problem: Upon entering the constructor of the other class, the object of the first class is gone and I can't access it's properties unless I define an instance of the first class...
Must I pass the object of the first class to the other class or is there another way of doing this?
Class1
def Class1 < handle
properties (Constant)
f = 1:2:20
g = 1:3:30
end
properties
a_Class1
b_Class1
c_Class1
end
methods
function obj = Class1(a,b,c)
obj.a_Class1 = a;
obj.b_Class1 = b;
obj.c_Class1 = c;
for k = 1:10
x(k) = Class2(k,f(k),g(k))
end
end
end
end
The values for a,b and c are user-specific values...
I need to access the values a,b and c in Class_2 without having to pass the whole object of Class1 to Class2...
The properties a_Class1, b_Class1 and c_Class1 are the same for both classes ...
Thank you for your advice!

Accepted Answer

Sebastian Castro
Sebastian Castro on 12 May 2017
This is expected. x is a local variable to the constructor, so it will go out of scope after instantiating the object.
You have two options:
  • Declare x as a property of Class1
  • Use functions such as assignin or evalin to stick x into the MATLAB base workspace (or the function where the Class1 object is instantiated)
I'd strongly recommend going with the first option.
- Sebastian
  1 Comment
Ahmed Hossam
Ahmed Hossam on 12 May 2017
Before reading this answer, I actually declared the a,b and c as properties of the other class. I think that's the best thing to do for now.

Sign in to comment.

More Answers (0)

Categories

Find more on Software Development Tools in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!