How can I create an array of class handles?
Show older comments
I'm a C++ developer and need to find an equivalent to a vector of class pointer: std::vector<MyClass*>
I have my Matlab classes inheriting handle already but what would be the appropriate container to use in Matlab for the vector part?
Thanks in advance.
Accepted Answer
More Answers (1)
If you mean a vector of class objects all of the same type then you just put them in an object array that behaves like a numeric array:
myObjectHandles = [obj1, obj2, obj3];
etc.
If you want to mix and match classes of a hierarchy that are not all the same type you have to do a bit more work, but unless that is what you mean I won't clutter my answer with that to start with.
Object arrays do have some nice properties. For example if your class has a property 'value' you can type:
myValues = [myObjectHandles.value];
to get an array of the 'value' property from each of the objects in your array also.
2 Comments
"Object arrays do have some nice properties". Yes, however object arrays is also something that can trip people coming from other languages where an array of object and a scalar object are two completely different types.
In matlab, myObjectHandles is a 1x3 MyClass array, while obj1 is a 1x1 MyClass object. They both have exactly the same methods, and when you invoke any method of MyClass (e.g. MyMethod(obj, args)), in the first case, obj will be a 1x3 MyClass object, while in the 2nd it will be a 1x1 MyClass object. This is something that will cause problems (it did for me anyway) if you write your method the same as in C++ where the this object is always scalar.
Nowadays, I tend to prevent array of object creation / concatenation in my class by default and only allow it when I've made the explicit effort of making sure my class methods all work with non-scalar objects.
Adam
on 15 Nov 2016
Yeah, I use object arrays for storage, but I don't support them in every function of the class as that is just too much work. I am happy to just use a for loop for that even though I know a for loop outside of a class is less efficient than one inside potentially (depending on how it is coded), but I've only found that to matter in a handful of cases where speed is really critical.
Categories
Find more on Construct and Work with Object Arrays 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!