Written by Sai Sandeep Thota on May 4, 2013 in C++ > Programming

C++ Program to Concatenate Two Strings using Operator Overloading

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this program we are performing concatenation of two strings using Operator overloading and Dynamic memory allocation. First we are finding the length of the given string using strlen and allocating a char size equals to the length of the respective string.

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

class string {
	public:
	char *s;
	int size;
	void getstring(char *str)
	{
		size = strlen(str);
		s = new char[size];
		strcpy(s,str);
	}

	void operator+(string);
};

void string::operator+(string ob)
{
	size = size+ob.size;
	s = new char[size];
	strcat(s,ob.s);
	cout<<"\nConcatnated String is: "<<s;
}

void main()
{
	string ob1, ob2;
	char *string1, *string2;
	clrscr();

	cout<<"\nEnter First String:";
	cin>>string1;

	ob1.getstring(string1);

	cout<<"\nEnter Second String:";
	cin>>string2;

	ob2.getstring(string2);

	//Calling + operator to Join/Concatenate strings
	ob1+ob2;
	getch();
}

Output:
Concatenate Two Strings using Operator Overloading

{ 2 comments… read them below or add one }

Aabhusan April 20, 2017 at 3:42 pm

I think ob1+ob2 should be ni ob3
I.e. ob3=ob1+ob2;
Ob3.operator+();
Correct me if I am wrong.

Reply

Myrtis October 1, 2017 at 12:36 pm

A great way to make sure that your synthesis connection makes sense is to clarify it to another person.

Reply

Leave a Comment

Previous post:

Next post: