Search code examples
c++const-reference

Const references for exposing fields


I have a class Date. let date be:

class Date
{
private:
    unsigned int _day;
    unsigned int _month;
    unsigned int _year;
public:
    const unsigned int& Day;
    const unsigned int& Month;
    const unsigned int& Year;

    Date() : Day(_day), Month(_month), Year(_year)
    {  }
}

For some reason, after the constructor is called Day, Month and Year do not point/refer to _day, _month and _year.

One guess of mine would be that they are being set before memory is allocated to the class, how would i go about solving this issue (aka setting the references after memory allocation)?

Thanks in advance!

EDIT: More info

The value of _day (for eg) is not returned when i get the value of Day. I get a seemingly random number.


Solution

  • It's not very clear what you want to achieve. In your Date class you can access _date, _month, _year directly why do you want to set another reference?

    But to answer you question

    The value of _day (for eg) is not returned when i get the value of Day. I get a seemingly random number

    Actually, the values are being returned, but you are getting garbage because _day, _month, and _year are just uninitialized integers. You need to initialize them in the initializer list first:

    Date() : _day(0), _month(1), _year(2), Day(_day), Month(_month), Year(_year)