c++

Can any one give me an explanation for the below program

#include <iostream.h>
#include <conio.h>
#include<string.h>

class strings
{
char s[10];
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<<"\nConcatenated string..."<<endl<<concatstr;
getch();
}


OK, this program first defines a "strings" class which holds a char array of 10 memebers. It's default constructor makes the array an empty c-string, while the constructor from a char*(c-string) copies the content of the string to the internal array. The class also defines a + operator, which concatenates 2 "strings" objects into a single c-string, and returns it. The main() program defines 2 "strings" objects, one with content "test", the other with content "run"(the \0 it not necessary, if not put in there, it would be added automagically), and then concatenates them in the c-string concatstr, which it then prints out.
Last edited on
Here, string is a class.
1
2
3
4
strings()
{
s[0]='\0';
}

//A COSTRUCTOR (use is not required in the prescence of the next parameterised one)
1
2
3
4
strings(char *c)
{
strcpy(s,c);
}


//parameterised constuctor (copies the content of the string to the duplicate string as the array variables are taken by the compiler directly without any formal parameters)

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

//overloading of a+ operator to concatenate two strings

and finally its the main function...concatenating two strings test & run...
Topic archived. No new replies allowed.