PDA

View Full Version : qobject_cast "good coding practice"



janus
17th October 2008, 11:40
Hi,

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:

mainwindow.cpp

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);
m_model->doSomething();


2. childwidget.cpp

void ChildWidget::setTableModel( MyQSqlTableModel *model )
{
m_model = model;
m_model->doSomething();

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

caduel
17th October 2008, 12: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.)