-1

Some c++ STL containers provide getters like

Foo.first

Foo.second

which apart from being very practical, improve code readability. Now suppose that I want to reproduce that feature in one of my own classes. Is it possible to define methods like

Matrix.components

Matrix.size

instead of

Matrix.components()

Matrix.size()

(same but without parentheses)? How could it be achieved?

JBL
  • 12,588
  • 4
  • 53
  • 84

2 Answers2

1

The .first and .second members are data, not code. Thus it doesn't make sense to "call" them. You methods aren't data, they're code, so you'd have to call them using (). Note that .size() is a method on all STL containers, never a data member.

MSalters
  • 173,980
  • 10
  • 155
  • 350
1

No, because this is how you access public member variable in C++.

The container you refer to must be an std::pair and that's its public member variables (the two elements of the pair) that are accessed this way, i.e. data and not functions.

For your matrix, either make these member variables (but that's a bad idea regarding encapsulation), or leave them as functions (like many container in the standard lib do).

JBL
  • 12,588
  • 4
  • 53
  • 84
  • OK. So there is a compromise between data encapsulation and code readability (annoying parentheses). –  Nov 10 '14 at 17:48
  • @Alejandro It's not a compromise. It's simply a matter of syntax. The parentheses aren't annoying, they denote a function. A function is completely different from a member variable, right? So let's not mixup the two different concept with the same syntax. (Like it's been the case already with the most vexing parse). – JBL Nov 10 '14 at 19:22