I come from a Java background and recently decided to try creating a C++ Qt GUI application “for fun”. I’ve been struggling with many of the finer differences between Java & c++, but I’ve learned a lot.
I’m attempting to match “java-style” syntax as closely as possible in my C++ coding. While this may or may not be a “best practice” for C++, I feel it helps when learning to keep a familar & consistent syntax. One of the java syntax carryovers is this:
//Java
MyObject o = new MyObject();
//C++
MyObject o = MyObject();
Now, I understand C++ has a syntax shortcut for the above:
//C++
MyObject o();
This is nice and all, but as I said, I don’t want to use different syntax, yet. Everything was working fine, but I received a surprise when I attempted the following Qt code:
QString filepath = "C:\\somefile";
QFile file = QFile(filepath);
And got a compile error:
c:\QtSDK\Desktop\Qt\4.7.2\mingw\include/QtCore/qfile.h:195: error: 'QFile::QFile(const QFile&)' is private within this context
I read the Qt docs and discovered that there is indeed no public constructor QFile::QFile(const QFile&). Where my code previously worked for other classes, there was such a constructor. I can make a guess here and say that the line:
QFile file = QFile(filepath);
is actually making calls to two constructors. Can someone explain?
These are not equivalent. The c++ version creates a new object, on stack, something java can only do with primitive types. Once
ogoes out of scope it will be destructed. What actually happens above is logicallyMyObject o(MyObject());(incorrect actual syntax) – construction followed by copy-construction.This is as close as you gets to your java version. The caveat, of course, is that in C++ you’ll need to also
delete o;– it’s not going to get garbage collected.This creates a temporary QFile, again on stack, and then creates
fileby copy-constructing it from the temporary. It is equivalent toQFile file(QFile(filepath));. In your case this will not work, QFile does not allow copy construction, so you’ll need to avoid the temporary by constructing QFile directly,