Why doesn’t std::vector or other containers have length as a member variable, instead of a function?
Because it would be writable if it was a public member variable. Since it makes no sense to write to the size member of a vector, the designers made the size member private and provided a size()
method to read its value. A java array’s length
member is declared final
so you can’t change it. You could do the same thing in C++ with a const
length member, but std::vector
needs to be able to change its length
, so that doesn’t make sense either. That’s the same reason java’s ArrayList
class uses a size()
method rather than a public member (that and so that it can provide dynamic dispatch through the List
interface).
Reading a vector’s size using a function is more costly than a member variable.
It really isn’t. The method’s definition is available at the point of the call, so the call will almost certainly be inlined by any decent compiler. In the end, the compiler will end up generating the exact same machine code for a public member variable or an accessor method.
2
solved Why doesnt vector support size as member variable like length variable in a Java class, instead a function size()? [closed]