I'm using Mysql 5.6 with Qt5 and creating a class to encapsulate a database connection.
When I try to create an object in the main with dbConnect conn = new dbConnect("localhost", "test1","test","user"); I get and error telling me I need a conversion from dbConnect* to a non-scalar type.
Reading other posts I've seen this could be due to the type of inicialization I'm trying because it's not a good practice in C++ and should be something like dbConnect conn("localhost", "test1","test","user"); but, changing it like that, instead of getting the conversion error I get now a no matching function for call to QSqlDatabase::setHosTname(std::string&) and same with the other methods needed for connecting such as setDatabaseName, setUserName and setPassword
Could it be because of the std::string I'm using?
Or how should I create the object?
This is m y header db.h:
#ifndef DB
#define DB
#include <QSqlDatabase>
#include <string>
class dbConnect:QSqlDatabase
{
public:
dbConnect(std::string host, std::string name,std::string user, std::string pass);
bool createConnection(std::string host, std::string name,std::string user, std::string pass);
private:
QSqlDatabase dbObject;
};
#endif // DB_
Next here it is its implementation db.cpp:
#include<QSqlDatabase>
#include <QMessageBox>
#include <QSqlError>
class dbConnect:QSqlDatabase
{
private:
QSqlDatabase dbObject;
public:
dbConnect(std::string host, std::string name,std::string user, std::string pass)
{
if(createConnection(host, name, user, pass))
{
QMessageBox::information(0,"Connection Status","Connection established with database");
}
else
{
QMessageBox::critical(0,QObject::tr("Error connecting to database"),dbObject.lastError().text());
}
}
bool createConnection(std::string host, std::string name,std::string user, std::string pass)
{
dbObject = QSqlDatabase::addDatabase("QMYSQL");
dbObject.setHostName(host);
dbObject.setDatabaseName(name);
dbObject.setUserName(user);
dbObject.setPassword(pass);
if(!dbObject.open())
{
return false;
}
else
{
return true;
}
}
};
UPDATE
Took @gengisdave and @R Sahu solutions and now I'm trying to create an object in the main. If I try dbConnect conn(); it works fine even if the constructor takes for paremeter but, if I trye dbConnect conn("localhost","test1","test","user"); compiler gives me an error of undefined reference to dbConnect::dbConnect(std::string,std::string,std::string,std::string).