problems with operator+

Hi,
I am relatively new at c++. I am writing a code with
operators and i'm with some problems in this part.

Anyway, it appears an warning during the compilation:
warning C4700: uninitialized local variable 'temp' used.

I can't not to understand how put it on right way,
because in execution it shows a debug error: variable not initialized.
( I see, it is not initialized, but when i try do that
many errors occurs )
( initialized the variable, like this --- str_type temp(" "); )

The following code receives 2 strings then it would concatenate them.
warning C4700: uninitialized local variable 'temp' used.

If some one could help me, I appreciate.




#include <iostream>
using namespace std;

class str_type{
char *str;
public:
str_type operator+(str_type t);
str_type operator=(str_type t);

void show(void);
void assign(char *chrs);
};

// operator +. Overload the +.
str_type str_type::operator+( str_type t)
{
str_type temp;

strcpy( temp.str, str );
strcat( temp.str, t.str );
return temp;
}

// operator assign . Overload the =.
str_type str_type::operator=( str_type t)
{
str = t.str;
return *this;
}

// show strings
void str_type::show(void)
{
cout << str << "\n";
}

// Assign strings
void str_type::assign(char *chrs)
{
str = chrs;
}

int main()
{
str_type a, b, c;

a.assign("string 1");
a.show();

b.assign("string 2");
b.show();

c = a + b;
c.show();

return 0;
}




As you say, the warning is because you are not initializing temp. The reason you can't do str_type temp(" ") is because you have not defined a constructor that takes those parameters. You need to declare temp, then define it's members manually or define a constructor that takes those parameters.
In first place, I want to thank for the time you spent on this problem.
But, I think my dificult is to define a constructor that takes those parameters,
or it is with strcpy statement
I have tried this but with another code, with a constructor like you said,
and there was the same result.

here, another code with the same problem if you don't mind.

#include <iostream>
using namespace std;

class caract{
char *temp;
public:
caract(void);
~caract(void);
void assign(char *str);
void show(void);
};

caract::caract(void)
{ temp = "hello ";}

caract::~caract(void)
{ cout << "destroyed\n";}

void caract::assign(char *str)
{ cout << temp;
cout << str << "\n";
strcpy(temp,str);
cout << temp << "\n";}

void caract::show(void)
{ cout << temp << "show \n";}

int main()
{ caract a, b, c;

a.assign("mike");
b.assign("however");
c.show();
return 0;}

I appreciate a suggest for this problem, it seems the same but I'm not get it.


This is going to seg fault.

temp is initialized in the constructor to point to a string literal. Most compilers will put the string literal into code space. Thus temp points
to read-only memory.

assign() does a strcpy() which then attempts to copy the string to
code space.

Topic archived. No new replies allowed.