Uninitialized reference element in C ++

I made a class in C ++, and I wanted it to have an Osoba& field, but I get a 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; } }; 
+4
source share
2 answers

Use the initialization list as follows: (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 the link as a member, and the link should be initialized immediately. This notation allows you to initialize the time of the announcement. If you used a regular member without & , it would work just fine, as you did. Although the style presented here is more effective.

Alternative: (Less effective 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; } }; 
+9
source

You need to use the constructor initialization list

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

You can see from your code that you lack basic C ++ knowledge, which is good, but please refer to a good book

+2
source

Source: https://habr.com/ru/post/1481617/


All Articles