Qt: error message telling the copy constructor is private

In the following code sample a singleton is implemented with a static instance getter which can be called in any other class.


class MyClass{

public:

    static MyClass *instance(){
        if(!m_instance)
            m_instance = new MyClass;
        return m_instance;
    }

private:

    MyClass(){}
    ~MyClass(){}

    static MyClass *m_instance;
};

MyClass *MyClass::m_instance = NULL;

class SomeOtherClass{
    void doSomething(){
        MyClass *c = MyClass::instance();
    }
};

In SomeOtherClass the method doSomething() grabs the instance of MyClass and keeps it in a local pointer variable. Now if the asterisk * is forgotten, the variable c no longer defines a pointer and in that case ‘=’ is no assignment but the copy constructor used to initialize the local variable declaration while the compiler complains this with a error message telling you that the copy constructor is private.

If in your Qt application the compiler outputs similar messages as follows, check if you’ve forgotten the asterisk.


/usr/include/qt4/QtCore/qobject.h: In copy constructor 'MyClass::MyClass(const MyClass&)':
/usr/include/qt4/QtCore/qobject.h:309: error: 'QObject::QObject(const QObject&)' is private
src/MyClass.h:17: error: within this context
/usr/include/qt4/QtGui/qstandarditemmodel.h:424: error: 'QStandardItemModel::QStandardItemModel(const QStandardItemModel&)' is private
src/MyClass.h:17: error: within this context
/usr/include/qt4/QtGui/qstandarditemmodel.h:424: error: 'QStandardItemModel::QStandardItemModel(const QStandardItemModel&)' is private
src/MyClass.h:17: error: within this context
/usr/include/qt4/QtGui/qstandarditemmodel.h:424: error: 'QStandardItemModel::QStandardItemModel(const QStandardItemModel&)' is private
src/MyClass.h:17: error: within this context

Note: the singleton implementation above has some drawbacks like not being thread-safe. Here it’s only used as a showing example.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>