0
votes

i need help to figure out what wrong about that code:

class DatabaseEngine
{
protected:
    DatabaseEngine();
    static DatabaseEngine* m_DatabaseEngine;
public:
    static DatabaseEngine& instance();
    void do_something();
};

cpp:

#include "databaseengine.h"

DatabaseEngine* DatabaseEngine::m_DatabaseEngine=nullptr;

DatabaseEngine::DatabaseEngine()
{
}


static DatabaseEngine& DatabaseEngine:: instance()
{
    if(m_DatabaseEngine==nullptr)
{
    m_DatabaseEngine=new DatabaseEngine;`enter code here`
}
return *m_DatabaseEngine;
}

void DatabaseEngine::do_something()
{

}

userwindow.cpp:

#include "databaseengine.h"
UsersWindow::UsersWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UsersWindow)
{
    ui->setupUi(this);
    DatabaseEngine::instance().do_something();
}

UsersWindow::~UsersWindow()
{
    delete ui;
}

userswindow.obj:-1: error: LNK2019: unresolved external symbol "public: static class DatabaseEngine & __cdecl DatabaseEngine::instance(void)" (?instance@DatabaseEngine@@SAAAV1@XZ) referenced in function "public: __thiscall UsersWindow::UsersWindow(class QWidget *)" (??0UsersWindow@@QAE@PAVQWidget@@@Z)

userswindow.obj:-1: error: LNK2019: unresolved external symbol "public: void __thiscall DatabaseEngine::do_something(void)" (?do_something@DatabaseEngine@@QAEXXZ) referenced in function "public: __thiscall UsersWindow::UsersWindow(class QWidget *)" (??0UsersWindow@@QAE@PAVQWidget@@@Z)

thanks

3
To me it looks like the cpp file for DatabaseEngine is not included in the project so Visual Studio is not compiling that code.drescherjm
BTW, One of the reasons I thought this was the error that both answers are mentioning. I saw that your .cpp file could not compile. So if you got no errors about that you either posted the wrong code or the file was not part of your project.drescherjm

3 Answers

2
votes

I think you need to remove the static keyword from your static function definition:

Wrong:

static DatabaseEngine& DatabaseEngine::instance()

Correct:

DatabaseEngine& DatabaseEngine::instance()
0
votes

declaration:

static DatabaseEngine& DatabaseEngine::instance();
   ^
only in declaration

definition:

DatabaseEngine& DatabaseEngine:: instance() {
   // code here
}

also make sure DatabaseEngine.cpp file is included in your project and is being compiled

0
votes

You can use static variable in the static method instance to hold the unique instance and return the pointer. This is also a smart advice from Effective C++ I think. The example is untested but it should work

class DatabaseEngine
{
public:
    static DatabaseEngine& instance(){
        static DatabaseEngine db;
        return db;
    }
};