Is the QChar constructor being called to initialize these objects?
Hi,
I am currently on Chapter 3 of C++ GUI Programming with Qt 4, Second Edition. And in this chapter it looks like two char arguments are passed to a function that requires two QChar arguments. To my understanding QChar is a class, so there must be some way that the char data is passed to the QChar class. Is this data passed to the QChar class by use of it's constructor (even though it's passed as an argument)? Is this unique to Qt or does it happen often in pure C++ also?
I looked at the Documentation of QChar and it looks like it's possible to pass char data to a QChar object's constructor by something like this:
example.cpp
sortdialog.cpp
Code:
void SortDialog
::setColumnRange(QChar first,
QChar last
) {
...
}
mainwindow.cpp
Code:
void MainWindow::sort()
{
SortDialog dialog(this);
dialog.setColumnRange('A' + range.leftColumn(),
'A' + range.rightColumn());
...
}
I even made a short program to test this:
main.cpp
Code:
#include <iostream>
using namespace std;
class myClass {
public:
myClass()
{
banana='b';
}
myClass(char tmp): banana(tmp)
{
//banana=tmp;
}
char getBanana(){
return banana;
}
char banana;
};
void createTMPClass(myClass tmp) {
cout << "tmp is " << tmp.banana << endl;
}
int main()
{
cout << "Hello World!" << endl;
myClass foo;
myClass bar='c';
cout << "foo is " << foo.banana << "\nbar is " << bar.banana << endl;
createTMPClass('d');
return 0;
}
OUTPUT
Code:
Hello World!
foo is b
bar is c
tmp is d
If my understanding is correct, this is a constructor being called not a copy constructor. What is this called when passing one data type (like 'char') to a function, where the function's argument (like 'QChar') uses that data type('char') for it's constructor? Is it called casting?
I've been Googling and can't seem to find anything like this. I can find details around constructors and assignment operators, but not specifically of passing two data types to a function that requires two classes. Like this page doesn't describe it:
http://www.learncpp.com/cpp-tutorial...ment-operator/
Re: Is the QChar constructor being called to initialize these objects?
That is an implicit type conversion.
The C++ compiler is allowed to do these if it has an argument of type A and needs type B and there is a constructor of B that takes A (and either not other arguments or all other arguments have default values).
In your case that is true for the char -> QChar conversion because QChar has a constructor with a single char argument: http://doc.qt.io/qt-5/qchar.html#QChar-9
Cheers,
_
Re: Is the QChar constructor being called to initialize these objects?
Thank you so much for letting me know what this called. I'm going to google more about it and so far I think I understand it.