Reputation: 5106
I have a following class which handles escape key press.
class KeyPress : public QWidget
{
Q_OBJECT
public:
KeyPress(QWidget * parent=0);
protected:
void keyPressEvent(QKeyEvent * event);
};
And the .cpp file:
void KeyPress::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape) {
qApp->quit();
}
}
It works fine, but if I change the method's name, to say, keyPressed(QKeyEvent * event)
, it doesn't work. The keyPressEvent(QKeyEvent * event)
method according to docs is a protected method of QWidget
.
So the initial code just overloads that method, dosn't it? And the overload works. But why a completely new version of the method with another name but the same implementation wouldn't work?
Upvotes: 0
Views: 368
Reputation: 9394
It is not overload
, it is override
of virtual
function.
Read about c++
virtual
functions.
For example:
#include <iostream>
using std::cout;
struct Foo { /*virtual*/void f() { cout << "foo:f\n"; } };
struct Boo : public Foo { void f() { cout << "boo:f\n"; } };
int main()
{
Boo boo;
Foo *ptr = &boo;
ptr->f();
}
such code print foo:f
, because of for ptr->f()
compiler generate something like this:
address_of_function = &Foo::f;
call address_of_function
but if you uncomment virtual
in my example code will print boo:f
,
because of virtual
cause compiler generate similar to such code:
address_of_function = ptr->virtual_table_of_Foo_class[offset_of_f]
call address_of_function
ptr
point to Boo class virtual table, and address_of_function
will be equal &Boo::f
, this how virtual
functions works.
So in your case Foo
== QWidget
and it have code like this inside of Qt
:
this->keyPressEvent();
, which take address of keyPressEvent
in virtual table, and call it. Obviously if you implement KeyPress::someOtherFunction
, it will be not called, because of already compiled code of Qt
have no call to it.
Upvotes: 2