In C++, When Should I Make A Method Constant? - c++

My question title pretty much asks it all. I've recently found out that it is good programming practice in C++ to pass many values by const reference and mark certain methods in classes as a constant method. Right now, I have a library that I have been writing for myself for a while now that has absolutely no const-correctness, so I'd like to start rectifying that little by little.
In what specific scenarios should I make a method constant? So far I know "getter" methods should generally be made constant (since the code in one shouldn't modify any class variables), but do I do that for all methods that are considered getters, or only specific ones? And outside of getter methods, what other scenarios should methods be made constant?

but do I do that for all methods that are considered getters, or only specific ones?
You should do that for all methods that don't modify the non-mutable members. They include not only getter functions but also any overloaded operator functions, such as operator==, operator!=, operator<.

When should I make a method constant?
As a rule of the thumb, you should make a method constant whenever none of the object's member variables are altered.
As an additional guideline, you should do this only when you are sure the method will not be altered in the future to change member variables.
Ultimately, if you are planning to make a method affect member variables, it should be non-constant. Otherwise, it should be constant.

Related

forcing a function to be pure

In C++ it is possible to declare that a function is const, which means, as far as I understand, that the compiler ensures the function does not modify the object. Is there something analogous in C++ where I can require that a function is pure? If not in C++, is there a language where one can make this requirement?
If this is not possible, why is it possible to require functions to be const but not require them to be pure? What makes these requirements different?
For clarity, by pure I want there to be no side effects and no use of variables other than those passed into the function. As a result there should be no file reading or system calls etc.
Here is a clearer definition of side effects:
No modification to files on the computer that the program is run on and no modification to variables with scope outside the function. No information is used to compute the function other than variables passed into it. Running the function should return the same thing every time it is run.
NOTE: I did some more research and encountered pure script
(Thanks for jarod42's comment)
Based on a quick read of the wikipedia article I am under the impression you can require functions be pure in pure script, however I am not completely sure.
Short answer: No. There is no equivalent keyword called pure that constrains a function like const does.
However, if you have a specific global variable you'd like to remain untouched, you do have the option of static type myVar. This will require that only functions in that file will be able to use it, and nothing outside of that file. That means any function outside that file will be constrained to leave it alone.
As to "side effects", I will break each of them down so you know what options you have:
No modification to files on the computer that the program is run on.
You can't constrain a function to do this that I'm aware. C++ just doesn't offer a way to constrain a function like this. You can, however, design a function to not modify any files, if you like.
No modification to variables with scope outside the function.
Globals are the only variables you can modify outside a function's scope that I'm aware of, besides anything passed by pointer or reference as a parameter. Globals have the option of being constant or static, which will keep you from modifying them, but, beyond that, there's really nothing you can do that I'm aware.
No information is used to compute the function other than variables passed into it.
Again, you can't constrain it to do so that I'm aware. However, you can design the function to work like this if you want.
Running the function should return the same thing every time it is run.
I'm not sure I understand why you want to constrain a function like this, but no. Not that I'm aware. Again, you can design it like this if you like, though.
As to why C++ doesn't offer an option like this? I'm guessing reusability. It appears that you have a specific list of things you don't want your function to do. However, the likelihood that a lot of other C++ users as a whole will need this particular set of constraints often is very small. Maybe they need one or two at a time, but not all at once. It doesn't seem like it would be worth the trouble to add it.
The same, however, cannot be said about const. const is used all the time, especially in parameter lists. This is to keep data from getting modified if it's passed by reference, or something. Thus, the compiler needs to know what functions modify the object. It uses const in the function declaration to keep track of this. Otherwise, it would have no way of knowing. However, with using const, it's quite simple. It can just constrain the object to only use functions that guarantee that it remains constant, or uses the const keyword in the declaration if the function.
Thus, const get's a lot of reuse.
Currently, C++ does not have a mechanism to ensure that a function has "no side effects and no use of variables other than those passed into the function." You can only force yourself to write pure functions, as mentioned by Jack Bashford. The compiler can't check this for you.
There is a proposal (N3744 Proposing [[pure]]). Here you can see that GCC and Clang already support __attribute__((pure)). Maybe it will be standardized in some form in the future revisions of C++.
In C++ it is possible to declare that a function is const, which means, as far as I understand, that the compiler ensures the function does not modify the object.
Not quite. The compiler will allow the object to be modified by (potentially ill-advised) use of const_cast. So the compiler only ensures that the function does not accidentally modify the object.
What makes these requirements [constant and pure] different?
They are different because one affects correct functionality while the other does not.
Suppose C is a container and you are iterating over its contents. At some point within the loop, perhaps you need to call a function that takes C as a parameter. If that function were to clear() the container, your loop will likely crash. Sure, you could build a loop that can handle that, but the point is that there are times when a caller needs assurance that the rug will not be pulled out from under it. Hence the ability to mark things const. If you pass C as a constant reference to a function, that function is promising to not modify C. This promise provides the needed assurance (even though, as I mentioned above, the promise can be broken).
I am not aware of a case where use of a non-pure function could similarly cause a program to crash. If there is no use for something, why complicate the language with it? If you can come up with a good use-case, maybe it is something to consider for a future revision of the language.
(Knowing that a function is pure could help a compiler optimize code. As far as I know, it's been left up to each compiler to define how to flag that, as it does not affect functionality.)

Call class method without parentheses in c++

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?
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).
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.

static functions compiler optimization C++

I know that we should declare a function as static in a class if its a utility function or if we have to use in a singleton class to access private static member.
But apart from that does a static function provide any sort of compiler optimization too since it doesn't pass the "this" pointer? Why not just use the utility function through an already instantiated object of class? Or is it just a best practice to make utility functions as statics?
Thanks in advance.
The "non-passing-this" optimization can probably be done by the compiler once you turn the optimizations on. As I see it, a static function has rather idiomatic uses:
Implementing modules. There is a bit of overlap here with namespaces, and I would rather use namespaces.
Factories: you can make the constructor protected/private and then have several static functions (with different, explicit names) creating instances.
For function pointers: static functions do not require the slightly more complicated syntax of pointer to member function. That can be a plus when interacting with libraries written for C.
To keep yourself from using this and have the compiler to enforce it. It makes sense sometimes. For example, if you have a commutative operation that takes two instances, a static function that takes the two instances would emphasize (in my opinion) that the operation is commutative. Of course in many cases you would rather overload an operator.
In general a static function will ease namespace and "friend" clutter by prefixing an otherwise ordinary function with the name of a class, presumably because both are tightly related.
Static exists to associate a method with a class, rather than either:
Associating it with an instance of that class (like writing a normal, non-static member function).
Keeping it in the global namespace or whatever namespace you would otherwise be in (like declaring a function just in the file, not in a class).
Static says that 'conceptually this is something tied to/associated with this class, but it does not depend on any instance of that class'.
In more formal terms: a static member function is the same as a function declared outside of a class in all ways other than that it is part of that class's namespace and in that it has access rights to that class's private/protected data members.
Going back to your question:
There is no optimization gain here.
Utility function has nothing to do with it. It's whether or not it makes sense to scope the function in the class itself (rather than an instance of it).
It does not 'pass the this pointer' because there is no instance to speak of. You can call a static member function without ever invoking that class's constructor.

Inline getter and setter vs public variables

I saw that in some programs it is recommended the use of public variables instead of get and set functions for a better performance. I know that this is considered a bad practice. I also know that the compiler could make the get and set inline. Doesn't this mean that they behave like a variable with no performance fall-outs?
The compiler will most probably inline these functions (see how), and there will be no function call overhead. I would avoid the getter, setter, and public member variables and instead think why these are used and provide a function to do that in that class. Most of the getter, setter, and public member variables can be removed this way.
You can always expect compilers to inline trivial getters and setters and so you'll get identical performance.
There can be differences though, such as not being able to get a pointer or reference to the private member when using getters/setters if you're returning by value. Also, setters may have an extra copy or move operation.
Anyway, if you want public access then just use public variables. They are best practices.
They should be the same performance-wise, if the compiler really choses to make them inline. The inline keyword is just a hint for the compiler, it must not strictly obey it, and vice-versa: it can make a function that is not marked with inline keyword, an inline one.
However, if for some reason the compiler will not make them inline, you will obviously lose some performance on the calls.

Class function member not depending on the class members

Is there a good reason why should a class function member be part of the class if it does not depend on any of the members of the class?
No. In fact, you should prefer free-functions over member functions. Only functions that really need to operate on the members should be member functions, the rest should use them to provide functionality.
Assuming you mean "does not depend on any non-public members", Scott Meyers once answered a definite no to that question.
However, he focused only on encapsulation: encapsulation is improved by making those functions non-members.
Other considerations can, for example, include that you cannot call operator<< on a temporary if the operator is defined as a non-member. (Why would you ever want to do that? Well, for example to build up a string argument from constituent parts, iostream-style.)
And the considerations can include simply how natural and clear the usage notation is. The notation with nested calls (as for non-members) can be rather annoying and unclear. That's why we have -> as syntactic sugar for * dereferencing + member selection.
So, if you focus only on encapsulation, then move those member functions out of class, as Scott Meyers adviced. And otherwise, make an engineering decision where aspects such as usability and notational clarity are also considered. Anyway, don't fret about it: it's probably not incredibly important. :-)
Cheers & hth.,
If its correlated with the meaning of the class, you should put it together even if it do not use any member of the Class.
The reason it for simply the development, and for a future developer know where to look.
It often happens when overriding a virtual function. If the base class has a pure virtual along the lines of getWidgetCount(), for example, and your derived class doesn't support widgets, it would just return 0.
the most common case concern utility classes for example if i have to develop functions to convert BSTR to string and vice versa , i can create a class with static methods.
it's useful to package functions concerning the same area in the same class, another solution is to package them in the same namespace, but unfortunatly namespaces are not very used even in the well known c++ librairies.
and for other cases adding method to a class with no relation with other members increase the lack of cohesion and the metric LCOM will be high, and the design will be impacted.