laurent
laurent

Reputation: 90736

Passing a variable by reference to another class

I'm trying to pass a variable by reference to a different class, but I cannot get it to work.

I have some config object that I create in the main application, then when I run the config dialog, I want to provide this config object to the dialog.

This is what I have so far:

ConfigDialog.h:

class ConfigDialog {

public:
    explicit ConfigDialog(kimai::Config& config, QWidget *parent = 0);

private:
    kimai::Config& config_;
};

ConfigDialog.cpp:

ConfigDialog::ConfigDialog(kimai::Config& config, QWidget *parent) {        
    config_ = config;
    // Do something with config_ - get/set values, etc.
}

When I try to compile, I get the following error:

ConfigDialog.cpp:7: error: C2758: 'ConfigDialog::config_' : must be initialized in constructor base/member initializer list

Any idea how to fix this issue?

(I tried adding config_ = config to the initialization list but this is not valid)

Upvotes: 1

Views: 710

Answers (5)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You cannot initialize a reference by assignment, it needs to be done in the initializer list:

ConfigDialog::ConfigDialog(kimai::Config& config, QWidget *parent) : config_(config) {        
    // Do something with config_ - get/set values, etc.
}

The config_ = config assignment is a call of the assignment operator on the value being referenced by config into the variable being referenced by config_, which is uninitialized. Assignment syntax works only when it is combined with the declaration:

int y = 5;
int &x = y;    // This works
int &z; z = y; // This does not work!
int w = 4;
x = y;         // This is an assignment to y through a reference

Upvotes: 3

Pablo
Pablo

Reputation: 8644

You should add it to the initialization list using constructor syntax:

ConfigDialog::ConfigDialog(kimai::Config& config, QWidget *parent)
    : config_ (config)
{        
    // Do something with config_ - get/set values, etc.
}

Upvotes: 0

Bojan Komazec
Bojan Komazec

Reputation: 9526

Error message told you everything. Try this:

ConfigDialog::ConfigDialog(kimai::Config& config, QWidget *parent) 
   :config_(config)
{           
    // Do something with config_ - get/set values, etc.
}

Class members of reference type must be initialized in the initialization lists.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

You have to use a constructor initializer list:

ConfigDialog::ConfigDialog(kimai::Config& config, QWidget *parent)
    : config_(config)
{
}

Upvotes: 3

Alex Bakulin
Alex Bakulin

Reputation: 1668

You should use initializer list to initialize a reference:

ConfigDialog::ConfigDialog(kimai::Config& config, QWidget *parent) 
        : config_(config)
{        
    // Do something with config_ - get/set values, etc.
}

Upvotes: 3

Related Questions