[SOLVED] Private object when they need to be allocated on the stack and when on the heap?
here some code
class MyClass : public QWidget
void do(QString& hello);
QString string;//doesn't give an error
QLabel label2;//error "error: field 'label3' has incomplete type"
//at the cpp
void MyClass::do(QString& hello)
string = hello;
label = new QLabel(this);//ok,no error
QLabel label3("hello");//seg error
qDebug() << string; //prints output,no error
these are my questions
1.why this "QLabel label2" produces a compiler error when "QString string" doesn't?
- why this "QLabel label3("hello")" produces seg error when this one "qDebug() << string;" doesn't
thanks in advance
I think that at "Qt in Education Course Materials":http://qt.nokia.com/learning/education/course-materials/ you will find the answers you are looking for. :-)
Well, those errors aren't directly related to Qt - those are C++ fundamentals.
When adding members to classes theirs sizes have to be known thus the compiler needs access to the members class definition. As you didn't include <QtGui/QLabel> the compiler has no information about the QLabel class (and its size). You do not need the class definition for pointers as pointers always have a fixed size, independent of the objects they point to. In such cases you are fine with a forward declaration, which tells the compiler that QLabel is a valid type defined somewhere and that it is valid to point to it (to create a QLabel* pointer).
There is no error thrown for QString as <QtGui/QWidget> includes <QtCore/QString> and thus it is included in your MyClass.h.
In addition I don't think line #23 causes a segmentation fault, but your comments generally do no match (there is no label3 in line #10).
[quote author="Lukas Geyer" date="1318537138"]Well, those errors aren't directly related to Qt -
In addition I don't think line #23 causes a segmentation fault, but your comments generally do no match (there is no label3 in line #10).[/quote]
Yes you have right,in the comment i meant label2.
There are 2 errors,the one in line 23 and the other in line 10.
I did a forward declare but error at line 10 occured
Yes, because you must not use a forward declare here (label2 is not a pointer, please re-read the previous post).
Line #23 is perfectly valid - I see no reason why your application should or could break here. If it actually does the error has to be caused somewhere earlier in your code. Please provide a small, compileable example which reflects your problem so we can actually find out what's going on.
Indeed. You can use pointers to classes that you only forward declare, because the size of a pointer is known, no matter what that pointer points to. But the size of the actual class is only know if you really have the declaration of that class available (like you do with a #include<QLabel>).
thank you for your answers.
@Lukas,indeed the line 23 was ok.The error was in some other part of my code