OOP/CPP String class to add two string and initialize using constructors

/*14. Define a class string that could work as a user defined string type.
 Include constructors dynamically that will enable
 to input a string from keyboard and to initialize
 an object with a string constant at the time of creation.
 Also include a member function that adds two strings to make a third string.
Write a complete program to implement this class.
*/
#include <iostream>
using namespace std;
#include<string.h>
class String
{ char *name;
int length;
public:
String( )// constructor-1
{
length = 0;
name= new char[length + 1];
}
String(char *s)// constructor-2
{
length = strlen(s);
name = new char[length + 1];// one additional
// character for \0
strcpy(name, s);
}
void display()
{
    cout<<name<<endl;
}
void join(String &a, String &b);
};
void String::join(String &a, String &b)
{
length = a.length + b.length;
delete name;
name = new char[length + 1];// dynamic allocation
strcpy(name, a.name);
strcat(name, b.name);
};
int main ( )
{
char *first;
cout<<“Enter the first name: “;
cin>>first;
String name1(first), name2(” Louis “), name3(” Lagrange “), s1, s2;
s1.join(name1, name2);
s2.join(s1, name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
      return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>