Reputation: 3184
I am running into a problem. I want to swap two Qt widgets:
void swap(QMainWindow **w1, QMainWindow **w2)
{
QMainWindow *w3;
w3 = *w1;
*w1 = *w2;
*w2 = w3;
}
However if I have widget1
of type MainWindow1*
and widget2
of type MainWindow2*
and I call swap(&widget1, &widget2);
I get
/home/user/Test/manager.cpp:24: error: invalid conversion from 'MainWindow1**' to 'QMainWindow**' [-fpermissive]
swap(&widget1, &widget2);
^
I must note that MainWindow1
and MainWindow2
are two QMainWindow
derived classes.
My question is: Is it possible to create a function that swaps at runtime two polymorphic objects? How can I get around this issue?
Thanks a lot!
Upvotes: 1
Views: 1338
Reputation: 24138
You should not be passing MainWindow1
and MainWindow2
pointers to swap like below.
MainWindow1* w1 = new MainWindow1();
MainWindow2* w2 = new MainWindow2();
swap(&w1, &w2);
If swap could happen in this case, MainWindow1
pointer would point to a MainWindow2
object, which is not right.
You have to pass MainWindow
pointers to swap like below.
MainWindow* w1 = new MainWindow1();
MainWindow* w2 = new MainWindow2();
swap(&w1, &w2);
Upvotes: 2