Is it possible to initialize reference variables later?

c++

Solution

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;
}

Problem

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?

Original source

Related problems