c++pointersreferencepointer-address

Pointer (address) with if statement


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,...);

Solution

  • 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, ... );