-
In different classes of Qt, I've come across functions followed by const keyword. Refer to the example below:
In QLabel Class; in public functions, there are following functions:
Function 1:QString text() const
Function 2:void setMargin(int)
In what way Function1 differ from Function2 except the operations they perform?
-
@Swati777999 said in constant functions in Qt Classes:
In what way Function1 differ from Function2 except the operations they perform?
You should really read a C++ book!
A const method is not allowed to change the state of the object on which it is called.
That means that text() will not change the internal state of the object (it will not change any internal variables). If you try to change the state of the object in a const method you will get compiler error. Especially getter methods are usually const methods because they simply return the value of an internal variable without changing anything.
A non-const method is allowed to change internal object state. For example setMargin(...) will change the margin in the object.Also, please ask such questions in https://forum.qt.io/category/34/c-gurus
-
-
@Swati777999 Qt is a C++ framework, so C++ syntax applies in C++ Qt applications. QML is based on JavaScript syntax. There are binding for Python also.
What you asked in this thread has nothing to do with Qt but belongs to basic C++ syntax, so please use correct forum for such questions. -
@Swati777999
Qt is not a combination of any languages. It is not a language, it is a library of functions. It is available for use from C++ or from Python (quite separately from one another). There is no JavaScript in anything you show, and JS is barely used in anything much from Qt.Your questions, or your question here, is just to do with C++. Nothing Qt about it.
-
https://www.geeksforgeeks.org/const-keyword-in-cpp/
const is a useful keyword in C++ and try to use it as much as possible whereever it is applied. It can avoid some silly bugs. -
@JoeCFD said in constant functions in Qt Classes:
const is a useful keyword in C++
const is a PITA keyword...too much culture of "protect people from themselves" for this old guy to stomach.
-
@Kent-Dorfman said in constant functions in Qt Classes:
@JoeCFD said in constant functions in Qt Classes:
const is a useful keyword in C++
const is a PITA keyword...too much culture of "protect people from themselves" for this old guy to stomach.
It's not just for protection. It also conveys the designer's intent for the API and it facilitates optimizations.
-
@Kent-Dorfman I swallowed it without any side effects. I know you will hate it.
-
@Kent-Dorfman said in constant functions in Qt Classes:
const is a PITA keyword...too much culture of "protect people from themselves" for this old guy to stomach.
Wow! Did you start out with C when it had no
const
keyword? -
@Kent-Dorfman
I'm with you :) Originally there wasn't anyvoid
either!