View Full Version : qobject_cast "good coding practice"

17th October 2008, 12:40

i wonder what is a better practice of passing pointers to childwidgets (if their is anything like a common good practice :) ) of this two possibilities: Passing the Baseclass or MyClass?

I have a MainWindow and need to pass a pointer to subclass of QSqlTableModel to a childwidget:


MyQSqlTableModel *tm = new MyQSqlTableModel;
ChildWidget *cw = new ChildWidget( this );
cw->setTableModel( tm );

1. childwidget.cpp

void ChildWidget::setTableModel( QAbstractItemModel *model )
m_model = qobject_cast<MyQSqlTableModel *>(model);

2. childwidget.cpp

void ChildWidget::setTableModel( MyQSqlTableModel *model )
m_model = model;

I have seen both and wonder what the difference is and what the better approach might be.

17th October 2008, 13:02
I prefer the 2nd. It states what really must be passed (whereas the 1st lets the compiler tolerate errors that will manifest themselves at runtime).
(Exceptions are when you inherit a class and have no choice in the signature.)