Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
[SOLVED] handling instances of QColor
planarian last edited by
Typically, are parameters of type QColor passed by value or reference? I know objects are usually passed by reference, but I'm a bit puzzled by expressions like "Qt::black." If I declare
@void somefunction (QColor *)@
is it legal to write:
DerManu last edited by
QColor is mosty passed by const reference (not pointer as in your example!). Effectively this is closer to a pass by value, because the QColor, if stored inside the function you pass it to, gets copied.
I don't recommend you use somefunction(QColor*) unless the function explicitly needs to modify the QColor and the caller of the function wants and expects the function to modify it. An example would be a function stripAlphaComponent(QColor* color); which strips the alpha of the passed QColor.
In all other cases you should prefer somefunction(const QColor &color);
The reason you can pass Qt::black instead of a QColor object is C++: If a function expects a certain class instance as parameter, the function additionally accepts all types from which such an instance can be created uniquely with a constructor of that class. In this case, QColor offers the constructor
QColor::QColor ( Qt::GlobalColor color )
Thus, when you pass Qt::black (which is a Qt::GlobalColor), C++ is smart and sees that there is a unique way to turn a Qt::GlobalColor into a QColor object by calling that constructor, and does it for you. Behind the scenes, these two calls are identical:
if somefunction takes a QColor or a const QColor & (not a QColor*!).