OOP- instantiate a class within a method of a different class
4 views (last 30 days)
Show older comments
Hi, I have 2 class files, both stored under the same folder. I want to instantiate class A in one of the method of class B but I get an error message: Undefined function or variable 'A'. how can "connect" between the 2 class files so that they know each other? Thanks!
8 Comments
Adam
on 21 Mar 2018
So it should be able to see it whether inside or outside of your other class, in that case.
Answers (1)
Guillaume
on 22 Mar 2018
For somebody coming from C++, I'm surprised you're not using private/public qualifiers for your class methods, rather than having everything public.
The problem with the visited class not being visible is puzzling since which can find it. It's surprising that it is in a bin directory but that doesn't matter.
Irrespective of that issue however, the whole concept of creating a handle class just to emulate a pass-by-reference array is extremely misguided. Matlab is not C++. If you need a mutable object in and out of a function, then you pass it as input and output. Therefore, the proper way to write your DFS would be:
methods
%... constructor, etc.
%DFS method. Note: I prefer calling the object 'this' rather than 'obj'
function DFS(this)
visited_size = this.nodes_num + 1;
visited = zeros(1, visited_size);
for i = 1:this.nodes_num
if visited(i) == 0
visited = DFSutil(this, i, visited);
end
end
end
end
methods (Access = private)
function visited = DFSutil(this, start, visited)
disp(start)
visited(start) = 1;
for i = drange(1:numel(this.vector_of_adj{start}))
if visited(this.vector_of_adj{start}(i)) == 0
visited = DFSutil(this, this.vector_of_adj{start}(i), visited);
end
end
end
end
Note that in the above case, matlab's JIT compiler should be able to detect that input and output are the same and pass the visited array by reference anyway.
See Also
Categories
Find more on Whos 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!