Program To Concatenate Two String Objects By Overloading The + Operator Using C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


The program first displays the contents of string objects s1, s2 and s3 before concatenation.The statement

s3 = s1 + s2;

on execution invokes the operator+ ( ) function through object s1 and object s2 is passed as an argument to the operator function.In the operator + ( ) function definition, an object temp of type string is created.Using the strcpy ( ) function, we copy the data member st of left object (s1 ) to data member of temp object.Then data member st of the passed string object s2 is added to the data member of the temp object, using strcat ( ) function.Finally the resultant temp object is returned to s3 object in main ( ) which is then displayed.

OUTPUT

Before concatenation

s1  =  Happy       s2  =   Diwali

After concatenation

s3   =  Happy Diwali