Access class methods in one line only when you use brackets after class name.

Hello, I'm hoping someone can explain why you can access a class method in a single statement only when you use brackets after the class name.
For example, I have a class called Data, with method stats. Why does Data.stats raise and error, but Data().stats does not raise an error.
The brackets are not required to instantiate the class, i.e. D = Data is the same as D = Data().
Thanks,
Dale.

 Accepted Answer

The phenomenon you are seeing goes beyond just classes. Data is the name of a function (the class constructor). As explained here, you can only directly dot-index the output of a function call if the parentheses are there, e.g.,
sfunc().a
ans = 1
sfunc.a
Using the dot operator to index into the output of function 'sfunc' is not supported.
function s=sfunc()
s.a=1;s.b=2;
end

3 Comments

As for why it is this way, I think it is just to help the efficiency of the parser. If the () are absent after the class name, the parser can more quickly and safely deduce that you are trying to access either a Constant property or Static method, and nothing else.
Thanks for your answer, that clarifies things. I assumed it wasn't MATLAB behaviour after trying to do multiple string splitting operations in a single line and it not working, but this could be quite useful.
And thanks for the follow-up comment explaining why.
If mymethod is an instance method (not a Static method, but one that requires an instance of the class on which to operate) a call like this:
myclass().mymethod
is almost always [*] equivalent to either:
mymethod(myclass) % A
mymethod(myclass()) % B
In either case, A or B, this calls the myclass constructor with no input arguments and passes the constructed object into the method.
This attempts to calls the method myStaticMethod as a Static method, not passing an instance into the method:
myclass.myStaticMethod
This calls that Static method with an instance of the class. This may work, or may not, depending on how the Static method is defined.
myclass().myStaticMethod
[*] There can be differences if the method accepts multiple input arguments, multiple objects are involved, and the objects have a specified class precedence relationship. See this page for some more details.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2023b

Asked:

on 5 Aug 2025

Commented:

on 6 Aug 2025

Community Treasure Hunt

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

Start Hunting!