Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

I have some error. Can anyone solve this??

0 votes
asked Nov 19, 2018 by anonymous
#include<iostream>

#include<string>

using namespace std;

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(void)

{cout << name << "\n";}

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 = "Joseph";

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;

}

1 Answer

0 votes
answered Nov 22, 2018 by gurik
At first you need to include cstring header to use strcpy, strlen, strcat functions. 

Also replace:
    delete = name;
with:
    delete name;

At last I think that you need to use other name for your class (something like my_string instead of string) becase string is already in use.
commented Nov 23, 2018 by Bartitch
Uhhh... There is a few.
As by gurik said don't use string. It already exist in std namespace.
Second... For delete:
delete = name;
use actually:
delete[] name;
When allocating array with new[] always use delete[]. There are reasons beyond cosmetic stuff. Some compilers may handle gracefully delete vs delete[]. But some may not. You may end up with some nasty memory leaks if you misshandle delete.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...