johnlowvale johnlowvale - 7 days ago 5
C++ Question

c++ assign a reference to property in constructor

I need to pass a database connection to a new object instance. However, the following code is not working as wanted.

class child {
public:
db_connection Con;
child(db_connection& Con);
};

child::child(db_connection& Con) {
this->Con = Con;
}


The assignment in constructor raises this error: use of deleted function....

I know this means it's calling constructor of db_connection to create new object of Con. But that's not what I wish to have.

And I can't declare the property 'Con' in class declaration as

class child {
public:
db_connection& Con;
...


Because a reference must be initialised or assigned. This is a hard situation.

Answer

As you noted, to be able to use a reference you need to initialize it. For that you should use a constructor initializer list:

class child {
    db_connection& Con;

  public:
    child(db_connection& con) : Con(con)
    {}
    ...
};

That initializes the member variable instead of assigning to it inside the constructor.