Search code examples
c++pointersgsoap

How to assign / convert pointers?


Please give some advice on pointers and conversion and assignment of values.

I have this fix class definition: (generated by gsoap)

class LibClass
{
public:
    std::string *email;    // pointer 
    int landId;                // no pointer
    // (....) much more
}

In a seperate function I assign data from a database (informix) to the class members above.

(...) // just database connection
// The following is informix interface related stuff
ITRow *row;
// define one time this conversions interface
ITConversions *c;
// placeholder for all string types, temporary data container
ITString its("");
ITString colname;

// read result from executed query 
while ( row = query.NextRow() ) {
    LibClass *ki = new LibClass;

     ki->email      = new (string);
     //ki->landId   = new (int);       // obviously : error: invalid conversion from 'int*' to 'int'

    // I tried : 
    // invent a new instance 
    LibClass rki;

     //rki = &ki;
     //rki.x        = 9;

     // this is okay but how to bring ki and rki together,
     int *a = new int;
     rki.x          = *a;

    // And for understanding, here's what comes next -  It seams as i have to hardcode all 30 DB fields... but thats okay for now.

    colname="email";
    ITValue *v = row->Column( colname );
    v->QueryInterface(ITConversionsIID, (void **) &c);
    c->ConvertTo( its );
    *( ki->email ) = string(its.Data());                   // THE DATA TRANSFER - assignment
    v->Release();

   } // while end

edit I couldn't continue with this so i cannot approve the suggestions but just want to close here and so i accept the most detailled answer. thx all.


Solution

  • First of all, LibClass should not have a pointer to a std::string unless there is a good reason. std::string internally handles all of the allocation for you.

    class LibClass
    {
    public:
        std::string email;         // shouldn't be a pointer 
        int landId;                // no pointer
        // (....) much more
    }
    

    And then inside your while loop, there is no longer a need to initialize email, and you can just assign the value you want to landId:

    LibClass ki;
    // ki.email is initialized to "" already
    ki.landId = 9;
    
    // ... other code ....
    ki.email = string(its.Data());
    

    Or, if LibClass must be a heap allocated for some reason (i.e. you need to pass it out of your function):

    LibClass *ki = new LibClass();
    // ki->email is initialized to "" already
    ki->landId = 9;
    
    // ... other code ....
    ki->email = string(its.Data());
    
    // IMPORTANT: somewhere else in your program you muse delete the allocated space
    delete ki;