0

I had a working code that gave me the address of a mesh (if i'm correct):

MyMesh &mesh = glWidget->mesh();

Now I want if thingie to assign different mesh adresses. One is mesh() first function and another function mesh(int): How is this done?

 MyMesh &mesh;  //error here: need to be initialized

 if(meshNum==0){
mesh = glWidget->mesh();
 }
 else if (meshNum==1){
mesh = glWidget->mesh(0);
 }
 else{
  return;
 }

 //mesh used in functions...
 function(mesh,...);
Matt
  • 22,721
  • 17
  • 71
  • 112
pazduha
  • 147
  • 3
  • 17

3 Answers3

2

References must be bound to an object at initialization ... you cannot have a default-initialized or zero-initialized reference. So code like:

MyMesh &mesh;

where mesh is a non-constant l-value reference to a Mesh object, is inherently ill-formed. At the point of declaration, you must bind the non-constant reference to a valid memory-addressable object.

Jason
  • 31,834
  • 7
  • 59
  • 78
2

If your case is simple enough that meshNum is constrained, you can use the ?: operator:

MyMesh &mesh = (meshNum == 0) ? glWidget->mesh() : glWidget->mesh(0);

Otherwise, you need a pointer since references must be initializated at the definition point, and cannot be reseated to refer to anything else.

MyMesh *mesh = 0;
if( meshNum == 0 ) {
    mesh = &glWidget->mesh();
} else if ( meshNum == 1 ){
    mesh = &glWidget->mesh(0);
}

function( *mesh, ... );
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
K-ballo
  • 80,396
  • 20
  • 159
  • 169
0

References are valid at all times in a well behaved program, so no, you cannot do that. However, why not just:

if(meshNum != 0 && meshNum != 1)
    return;
function((meshNum == 0) ? glWidget->mesh() : glWidget->mesh(0));

Or you could just use a pointer and deference it later:

MyMesh *mesh = 0;
if(meshNum==0) {
    mesh = &glWidget->mesh();
}
else if (meshNum==1) {
    mesh = &glWidget->mesh(0);
}
else {
  return;
}

function(*mesh);
Ed S.
  • 122,712
  • 22
  • 185
  • 265