Pls explain how this working??


#include<iostream.h>
#include<conio.h>
#include<string.h>
class strings
{
char s[20];
public:
strings()
{
s[0]='\0';
}
strings(char *c)
{
strcpy(s,c);
} char *operator+(strings x1)
{
char *temp;
strcpy(temp,s);
strcat(temp,x1.s);
return temp;
}
};
void main()
{
clrscr();
strings s1("test"), s2("run\0");
char *concatstr;
concatstr=s1+s2;
cout<<"\n Concatenated string"<<concatstr;
getch();
}


Can any one explain this step only. How will working this function.

strings(char *c)
{
strcpy(s,c);
}

char *operator+(strings x1)
{
char *temp;
strcpy(temp,s);
strcat(temp,x1.s);
return temp;
}
Use code tags please.

1
2
3
4
strings(char *c)
{
strcpy(s,c);
}

that's a constructor. copying the char array into your member variable 's'.
http://www.cplusplus.com/doc/tutorial/classes/

1
2
3
4
5
6
7
char *operator+(strings x1)
{
char *temp;
strcpy(temp,s);
strcat(temp,x1.s);
return temp;
}


overloading the addition operator so your class can concatenate strings together.
http://en.cppreference.com/w/cpp/language/operators
Mr. Mutexe
thanks for your response

Kindly explain the the two statement

1. Why compiler copy the two times from c to s

strings(char *c)
{
strcpy(s,c);
}

2. Why access the s through x1.s

strcat(temp,x1.s);

Please explain only

Why compiler copy the two times from c to s

It only copies once:

1
2
3
4
strings(char *c)   // <- this just passes it in to your object upon construction
{
    strcpy(s,c); // <- this is where the copy happens
}


Why access the s through x1.s

because s is a member variable of your strings class.

read this:
http://www.cplusplus.com/doc/tutorial/classes/
`temp' is uninitialized in `operator+'
Mr Mutexe

Sorry for frequently asked questions..

char *temp;
strcpy(temp,s);// value of s is copy to temp (test is copied to temp)
strcat(temp,x1.s); // value of temp and value of s is merging. (test and run are merging)
return temp; But how the return the value of temp (test run)

This is correct or not...

Why we assign temp is pointer variable?

please explain...

Thanks in advance...

can you post using code tags please?
And also take note of what new said. You haven't allocated memory for your temp pointer.
also include files ending in ".h" are "older" headers.
also void main should be replaced with int main.

i believe strcpy is an unsafe method too.
Topic archived. No new replies allowed.