Header file:
MainWindow(QWidget *parent = 0, ColumnHelper column_helper = ColumnHelper() );
.cpp
file:
MainWindow::MainWindow(QWidget *parent, ColumnHelper column_helper)
Usage:
SpreadColumnHelper column_helper;
MainWindow w(0,column_helper);
SpreadColumnHelper
is the derived class of ColumnHelper
.
But only the default ColumnHelper
class is obtained in Main()
.
EDIT
I want the derived class to be passed in MainWindow()
but the base class is passed. How can I pass the derived class?
Since the parameter of MainWindow
is declared as an immediate object of type ColumnHelper
, it will always be an object of type ColumnHelper
. It is impossible for it to somehow change its type, regardless of what you pass as an argument.
Trying to pass a SpreadColumnHelper
as an argument will only cause it to get "sliced" to its ColumnHelper
base subobject. That ColumnHelper
object will be received by MainWindow
(which is exactly what you observe).
If you want your column_helper
parameter to behave polymorphically, you have to declare it as either a pointer or a reference to ColumnHelper
, e.g.
MainWindow(QWidget *parent, ColumnHelper &column_helper)
or maybe
MainWindow(QWidget *parent = 0, const ColumnHelper &column_helper = ColumnHelper())
Note that providing a temporary object as a default argument is only possible if the parameter is declared as a const reference.