Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialized reference member in C++

I have made class in C++ and I wanted it to have a field Osoba& but I get an weird error:

class Rachunek{
public:
    Osoba& wlasciciel;
    double stan_konta;
    Rachunek(Osoba* wlasciciel, double stan_konta){ //Uninitialized reference member
        this->wlasciciel = wlasciciel;
        this->stan_konta = stan_konta;

    }
};
like image 242
Yoda Avatar asked May 19 '13 11:05

Yoda


People also ask

Can a reference be uninitialized?

Now as we know reference variable needs to be initialized at the same step so it will pop up an error message called “reference member is not initialized” .

How do you initialize const and reference member variables?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

How do you initialize a null reference in C++?

No, references cannot be NULL in C++. Possible solutions include: using a pointer instead of a reference. having a dummy Object instance that can be used to indicate "no object".


2 Answers

Use initializing list like this: (Best approach)

class Rachunek{
public:
    Osoba& wlasciciel;
    double stan_konta;
    Rachunek(Osoba* wlasciciel, double stan_konta): 
        wlasciciel(*wlasciciel) , 
        stan_konta(stan_konta)  { //Uninitialized reference member


    }
};

You have a reference as a member and a reference must be initialized right away. This notation allows for initialization at declaration time. If you instead used a normal member without & it would work fine as you did it. Though the presented style here is more efficient.

Alternativly: (Lesser efficient approach)

class Rachunek{
public:
    Osoba wlasciciel; // Note missing & on the type. 
    double stan_konta;
    Rachunek(Osoba* wlasciciel, double stan_konta)
    {
        this->wlasciciel = *wlasciciel;  
        this->stan_konta = stan_konta;  

    }
};
like image 162
CodeTower Avatar answered Sep 21 '22 01:09

CodeTower


You need to use the constructor initialization list

Rachunek(Osoba* wlasciciel, double stan_konta)
      :wlasciciel (*wlasciciel)
      ,stan_konta (stan_konta)
{ 
}

It is obvious from your code that you lack a lot of basic C++ knowledge, which is fine, but please do refer to a good book

like image 34
Armen Tsirunyan Avatar answered Sep 22 '22 01:09

Armen Tsirunyan