Hello,
Structure of my classes is as follows :
String.h
1 2 3 4 5 6 7 8 9
|
class String
{
public:
String();
String(char*);
ByteArray toByteArray();
private:
char* data;
};
|
String.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
String::String(char* data)
{
String::data=(char*)malloc(strlen(data)*sizeof(char));
memcpy(String::data,data,strlen(data));
}
String::~String()
{
free(data);
}
ByteArray String::toByteArray()
{
ByteArray temp(7); // returning ByteArray Object by value;
return temp;
}
|
ByteArray.h
1 2 3 4 5 6 7 8 9 10 11
|
class ByteArray : public Object
{
public:
ByteArray(int NoOfElements);
~ByteArray();
int length();
int8 valueAt(int);
private:
int8* data;
int datalength;
};
|
ByteArray.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
ByteArray::ByteArray(int NoOfElements)
{
data=(int8*)malloc(NoOfElements*sizeof(int8));
datalength=NoOfElements;
for(int i=0;i<datalength;i++)
data[i]=0;
}
ByteArray::~ByteArray()
{
free(data);
}
int ByteArray::length()
{
return dataLength;
}
int8 ByteArray::valueAt(int index)
{
return data[index];
}
|
Main.cpp
1 2 3 4 5 6 7 8 9 10 11
|
int main()
{
String s("alpha");
ByteArray b=s.toByteArray(); // getting ByteArray b by value
for(int i=0;i<b.length();i++)
{
int8 temp=b.valueAt(i);
SomeObject* so=new SomeObject();
}
return 0;
}
|
at line 4 of main() i get ByteArray object by value.
The ByteArray returned contains 7 elements all initialised to zero.
The for loop would traverse 7 times.
While traversing only the zero^th element returned by statement b.valueAt(i) is proper , rest all values are junk values as -77,-21...etc.
But when i remove statement SomeObject* so=new SomeObject();
i get proper values of object b.
==============
Then, i make when i changed the design as :-
instead of returning ByteArray by value i return it as a reference as :-
1 2 3 4 5
|
ByteArray* String::toByteArray()
{
ByteArray* temp=new ByteArray(7); // returning ByteArray Object by reference;
return temp;
}
|
then in such a secanrio i don't get junk values...
I am not able to understand this concept.
why do i get junk values of elements of ByteArray object when returned by value and it works fine if i return ByteArray Object by reference.
help appreciated
amal