For example here is my code
QScopedPointer<QTimer> timer2(new QTimer);
But I want to define
QScopedPointer<QTimer> timer2; 
in mainwindow.h and create an instance
timer2(new QTimer);
in the mainwindow.cpp
How?
For example here is my code
QScopedPointer<QTimer> timer2(new QTimer);
But I want to define
QScopedPointer<QTimer> timer2; 
in mainwindow.h and create an instance
timer2(new QTimer);
in the mainwindow.cpp
How?
 On
                        
                            
                        
                        
                            On
                            
                                                    
                    
                What you're doing amounts to a premature pessimization. You're creating members of a MainWindow class separately and individually on the heap, when you should be simply putting them into the class as members:
// interface
#include <QMainWindow>
#include <QTimer>
class MainWindow : public QMainWindow {
  Q_OBJECT
  QTimer m_timer;
public:
  MainWindow(QWidget * parent = 0, Qt::WindowFlags flags = 0);
};
// implementation
MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags flags) :
  QMainWindow(parent, flags),
  m_timer()
{
  ...
}
Of course, you would ordinarily not want to expose all the details of the MainWindow's implementation in the interface (header) file. Thus you would leverage the PIMPL idiom:
// interface
#include <QMainWindow>
class MainWindowPrivate;
class MainWindow : public QMainWindow {
  Q_OBJECT
  Q_DECLARE_PRIVATE(MainWindow)
  QScopedPointer<MainWindowPrivate> const d_ptr;
public:
  MainWindow(QWidget * parent = 0, Qt::WindowFlags flags = 0);
}
// implementation
#include "MainWindow.h"
#include <QTimer>
class MainWindowPrivate {
public:
  QTimer timer;
}
MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags flags) :
  QMainWindow(parent, flags),
  d_ptr(new(MainWindowPrivate())
{
  Q_D(MainWindow);
  d->timer.start( ... );
  ...
}
Try the following:
If you want to create the instance in the constructor, use the following:
Alternately, if you want to create the instance in some arbitrary member function of
MainWindow, use this:It's also worth reviewing initialization lists in C++ and the documentation for
QScopedPointer.