Home > Mobile >  QT C access to a Class Member of another Class
QT C access to a Class Member of another Class

Time:05-10

i really dont understand the following behavior:

3 Code snippets to explain

sqlconnection.h

class SqlConnection
{
public:
SqlConnection();
QSqlDatabase db;
} ;

sqlconnection.cpp

SqlConnection::SqlConnection()
{ if (!db.open()){ //no different with or without that
  db = QSqlDatabase::addDatabase("QODBC");
  ...
}

artikelverwaltung.cpp

Artikelverwaltung::Artikelverwaltung(){

 SqlConnection().db.open();
 ...(code to do works fine)
}
void Artikelverwaltung::on_pushButton_2_clicked()
{

SqlConnection().db.close(); // "HERE"
}

"HERE" it cycles the full Contructor of the Class again, but why it don't just close the connection? (this is the Main question about and how to fix that.)

I can't even access "db" from another Method inside the Class but outside of the Constructor, like:

sqlconnection.cpp:

void closeDB() {db.close();} is not possible.`

What i am doing wrong?

Thank you guys

CodePudding user response:

In general, you do not need to use any wrapper class to hold database connections in Qt. You should create a database connection once using QSqlDatabase::addDatabase and open it. After that you can get a database connection anywhere by calling QSqlDatabase::database static method. So to close the database connection you should simply call QSqlDatabase::database().close().

CodePudding user response:

Hello and welcome to Stackoverflow!

If you call SqlConnection().db.close();, what you are actually doing is creating a new instance of your SqlConnection class and then calling close() on its variable db. This is not the same one you opened earlier.

What you want to do is inside of your Artikelverwaltung class:

SqlConnection sqlConnection = new SqlConnection();

and then later

sqlConnection.db.open();

and afterwards

sqlConnection.db.close();

The reason why you cant add that closeDB() method is that you need to either put the method inside of the SqlConnection class or you need to operate on an instance of the class.

You cannot operate on a class like this without instanciating it (creating an instance of it).

You should look at class instantiation to understand how the concept works.

If you call SqlConnection() you are creating a new instance of the class (you can look at it like a copy of the class).
If you call SqlConnection() somewhere else you are simply creating a new instance.
These instances do NOT share the variables or the contents in them. They are completely independent.

You cannot access a member of a class (like your db variable) without creating an instance of the class first and then accessing the member of that instance.

  • Related