Enlighten, please, on the topic of constant methods in C ++; Why do we need, what are the advantages ?! With small code examples, if not difficult.
7 answers
Constant methods are used to determine what can be done with a class without side effects on its state, and what changes its state. A user of a class in which const correctly placed in some cases, for example, can avoid unnecessary copying of objects without losing data. Also, if const used correctly at the compilation level, a random change of the object in the method is excluded, which should not change anything in the object. For example, there is a class like
class A { int a; int b; public: int getA() { b = b + 1;return a; } int getB() { a = a + 1;return b; } }; Here mnemonics and semantics are a little inconsistent. I just want to think that if
A x, y; ... bool f = x.getA() == y.getA() && x.getB() == y.getB(); f true, x and y are somewhat similar, but the insides of the class are not implemented as such. The user of the class must be sure that the getter will not spoil anything. A good class developer must explicitly describe the behavior of a method using const or no const
class A { int a; int b; public: int getA() const { return a; } int getB() const { return b; } }; But if you suddenly need to do a prog, in which there is something like a count of accesses to a variable, then the semantics of the getters forces you to use const , but you need to increase the counter of references. For this case there is the word mutable ! With this word we mark the fields that seem to be members of a class, but they do not reflect its state.
class A { int a; int b; mutable int cntA; mutable int cntB; public: int getA() const { cntA++; return a; } int getB() const { cntB++; return b; } }; - 2mutable and const are a great example of the artificial difficulties of C ++. And in general - using getters and setters is not the best tone. In the sense that they do not need to be done on any variable within the class. It is better to have clear functions that make the action itself so that the logic of the work is inside the class. In addition, some of the parameters can be set when constructing an object (class instance). Something like that. - gecube pm
- Getter is one use case. You can think of others. C ++ can be used to create artificial difficulties - this is indisputable. This is the danger of any powerful toolkit. - yapycoder
A few words about the use of constant methods. Classes with constant methods are convenient to use:
1. When several programmers are working on the project. When a class is being designed, the developer immediately determines what can change under what conditions and what should remain unchanged. Constant classes here are just to the point for building all the "restraining fences" so that another developer does not accidentally change the state of the object. As a rule, classes with constant methods do not have a default constructor, but only constructors that depend on some objects. This is very convenient, since all members will be initialized. By the way, this is the only way to initialize constant members.
2. Using objects const. If a constant object is created, then constant methods must be used to refer to its methods and members. For example, if a pointer to an object is passed to a function, but you want to protect it from being modified, then you need to declare it as const
In non-static class methods, the compiler implicitly passes a constant pointer to the object from which the method was called, its signature
T* const this // адресс на который указывает this поменять нельзя thanks to him, it is possible to associate a call to variables and methods with the actual address of the instance. Hence the code:
void f() { m_a = 10; } is equivalent to
void f() { this->m_a = 10; } In cases with constant methods, you change two behaviors:
Now this method can be called for a constant object.
const Foo a; a->f(); // only if f() is const methodNow a constant pointer to a constant is passed into these methods.
const T* const this; // адресс и состояние объекта на который указывает this поменять нельзя
Consequently
void f() { this->m_a = 10; // ошибка нельзя менять состояние константного объекта } Advantages of the constant method:
- can be called for constant objects and pointers to a constant.
- applications of
grammar const(all that should be const - should have this specifier) - if the method does not change the object, then why should the programmer not explicitly indicate this to himself, other programmers and the compiler? You can overload the method through its constancy:
struct Array { int x; int operator[]( int index ) const { return x; } int& operator[]( int index ) { return x; } }; int main() { Array a; a[1] = 10; // int& operator[]( int index ) // ok const Array b; b[1] = 10; // int operator[]( int index ) const // error: `int` is not lvalue }
A constant method is a method that does not change the class itself. When you try to compile code that contains a constant function, the class changes the compiler will generate an error, only constant methods can be called on constant classes.
- that is, as I understand it, they cannot change anything in the class in which they are defined ?! - rojaster
- except mutable class members - yapycoder
- but they can tell something about what is in the class in which they are defined - yapycoder
Everything becomes clear if you understand how the class methods work.
class A { public: int GetSome(); void SetSome(int some); } For the compiler, any call to a class method essentially looks like this:
int GetSome(const A* const this); void SetSome(A* const this,int some); From which it is obvious that when you try to change a constant object, you will get your hands. And from this it becomes clear why friendly functions, static functions cannot be constant.
- and where to read about how for the compiler everything "looks" ?? that is, how does the compiler work with code? - rojaster 3:49 pm
- In the standard. - gecube
And now in Russian:
A constant method is a method that does not change the properties / members of a class. When trying to compile code that contains a constant method of changing a class, the compiler will generate an error. For constant objects, only constant methods can be called.
Constant functions are never. Like constant classes;)
- the expert had in mind most likely constant-objects_class - yapycoder
- I guessed, but the vehicle is not a fact. - niXman
- that is, if I want this method to not change the "state" of my class, then I specify a constant method? Type so that the compiler throws away if it suddenly changes at the compilation stage ?? - rojaster
- Yes, you specify it as constant. but if the body of the method suddenly tries to change the properties of the class, no exception will be thrown away. get a compilation error. - niXman
Very well everything is explained in the book by Jeff Alger. C ++: Programmer’s Library - SPb: Peter Publishing House, 2000. If I can, I can quote here from it.