Why can I assign QObject * to QObject?
Consider the following code:
#include <QObject>
class A : public QObject
{
Q_OBJECT
public:
A(QObject* parent = 0) : QObject(parent) {}
}
int main()
{
A a = new A();
return 0;
}
Why can I assign an object of a type to a type A*
variable A
without a compiler (or runtime) complaint?
source to share
In this code, the constructor is A
used to convert A*
to an object of the type A
instead of assigning it. In general, the compiler is allowed to implicitly use a match constructor as a conversion operator, so the following code is legal:
struct B
{
B(int i){}
}
int main()
{
B b = 5;
return 0;
}
The question code uses an unnamed parent
constructor argument as the result of the operator . This is permitted since it is derived from (and thus matches the argument list). However, this is clearly undesirable behavior, because it is not an object being returned , but an object of the type that was born for that object. (Also, the 'ed object is never d, which results in a memory leak.)A
A*
new
A
QObject
A
new
A
new
delete
To prevent such a small mistake, it is generally a QObject
good idea to create a constructor for nested classes explicit
to prevent the compiler from misusing it as a conversion operator. (This applies to situations like this, not just Qt.) With the following modified code, the compiler catches the error:
class A : public QObject
{
Q_OBJECT
public:
explicit A(QObject* parent = 0) : QObject(parent) {}
}
source to share