Jake Freelander
Jake Freelander

Reputation: 1471

Is it possible to initialize reference variables later?

Best explained with an example:

Class banana {
    int &yumminess;
    banana::banana() {
        //load up a memory mapped file, create a view
        //the yumminess value is the first thing in the view so
        yumminess = *((int*)view);
    }
}

But that doesn't work :/ there is no way I can know where the view is going to be when I dreclare the "yumminess" reference variable. Right now i just use a pointer and dereference it all the time, is there any way to bring this little extra bit of convenience to my class?

Upvotes: 4

Views: 897

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

In short: No, it's intentionally not possible.

Think twice: Something like uninitialized references cannot really exist; such wouldn't make sense at all.
Thus they'll need to be set at the time of construction of the enclosing class, or at a point of static initialization.

You'll need to use pointers for such case.


Besides note that

 yumminess = (int*)view;

would be wrongly casted (to a pointer) anyway.


"Right now i just use a pointer and dereference it all the time ..."

That's also easy to overcome writing an appropriate member function to access the reference.

int* yumminess;

// ...

int& yumminessRef() {
    if(!yumminess) { 
        throw some_appropriate_exception("`yumminess` not initialized properly.");
    }
    return *yumminess;
}

Upvotes: 6

Christian Hackl
Christian Hackl

Reputation: 27528

No, not directly.

If you think the pointer is inconvenient, have a look at std::optional.

Upvotes: 2

Related Questions