1

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?

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
v78
  • 2,803
  • 21
  • 44

3 Answers3

2

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

You sure that the default constructor of SpreadColumnHelper has different return value with default constructor of ColumnHelper? I guess that because these two default constructor has same realization.

Vincent
  • 84
  • 6
1

The reason is that the second argument to the function is passed by value. When passing an object of derived type, a ColumnHelper object is created, using only ColumnHelper parts of the supplied object and this is what the function receives. This is described as object slicing - a copy of only part of the passed object is received by the function.

Change the second argument to be a const reference (a non-const reference does not play well with default arguments specified as a value).

Peter
  • 35,646
  • 4
  • 32
  • 74
  • Thanks, for the clarification. It solved my problem. sorry, could not accept 2 answers unfortunately. – v78 Oct 08 '16 at 17:26