Hi,
I am not sure how to categorize my problem
I have a class with char* as member variables. and I am using a get method to print the variable. Now I create a vector and in to it, I am pushing the objects of the class. but while trying to print/access these class variables it is printing garbage values. let me simplify my code.
class employee {
private:
char* firstName;
char* lastName;
public:
char* getFirstName() const{
return firstName;
}
char* getLastName() const {
return lastName;
}
void loadEmpNameFromDb();
employee* fetchEmpRecord();
static std::vector <employee*> empVector;
};
that's what I have in my header file.
in the source or .cpp file I have the following code
employee::employee()
{//ctor}
employee::~employee()
{//dtor}
void loadEmpNameFromDb() {
char local_fname[30];
char* local_lname[30];
//next 3 lines of code should perform connecting to the Db and access the emp records.
DbConnection *db = new DbConnection(im_db_user, im_db_name, application, im_db_server);
if (sqlStatement->SQLexec("exec IM_get_NE_list_for_SUPI") == SUCCEED) {
if ((stat = sqlStatement->SQLget_result()) != SUCCEED) {
stat = sqlStatement->SQLbind("Dist_name", &local_fname, 31);
stat = sqlStatement->SQLbind("System_type", &local_lname, 31);
while() //looping for end of the records
{
employee* empObjPtr = new employee();
empObjPtr->firstName = local_fname;
empObjPtr->lastName = local_lname;
empVector.push_back(empObjPtr);
empObjPtr=NULL;
}
}
}
}
void employee:: displayEmpRecord() {
std::vector<employee*>::iterator cacheObjIter;
for(cacheObjIter = empVector.begin(); cacheObjIter ! = empVector.end(); cacheObjIter++) {
cout <<"first name =" <<(*cacheObjPtr)->getFirstName()<<endl;
cout<<"lastname=" <<(*cacheObjPtr)->getLastName()<<endl;
}
int main()
{
employee mycompanyemp;
mycompanyemp.loadEmpNameFromDb();
mycompanyemp.fetchEmpRecord() ;
}
I have put the code in a most simplified manner I could think of.
Now the problem I see is the output is a garbage values.
I see that I am able to iterate 5 times meaning there are 5 records in the db and everytime it is printing the last record values that are partially junk characters.
the expected out put is some what like this
firstname = john
lastname = smith
===========
firstname = jack
lastname = hammer
===========
firstname = jill
lastname = nelson
=========== etc.
but I get the following output :
firstname =
lastname= nelso00
===========
firstname =
lastname= nelso00
===========
firstname =
lastname= nelso00
===========
not sure of what went wrong. but I fiddled with this code for the whole day and yet couldn't resolve it. problem looks pretty simple. but still I am not able to fix it. please help me.