Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to overload binary + for concatenate two String & == to compare length of two String

C++ Code Example — Operator Overloading

ADVERTISEMENT

WAP to overload binary + for concatenate two String & == to compare length of two String

Objective

Write a C++ program to overload the binary (+) and equality (==) operators for custom String manipulation.

Algorithm / Approach

  1. Create a class String that holds a character array.
  2. Overload +: String operator+(String x). Inside, use strcat() to concatenate the internal arrays.
  3. Overload ==: int operator==(String x). Inside, use strlen() to compare lengths.
  4. In main(), use a + b to join two custom String objects and a == b to compare them.
main.cpp
#include<iostream>
#include<string.h>
using namespace std;
class String {
 public:
 char a[20];
 void getString(char x[]) {
  strcpy(a,x);
 }
 void display() {
  cout<< a<< endl;
 }
 String operator+(String x) {
  String obj;
  strcpy(obj.a,a);
  strcat(obj.a,x.a);
  return obj;
 }
 int operator==(String x) {
  int len1 = strlen(a);
  int len2 = strlen(x.a);
  return len1-len2;
 }	
};
int main() {
 String a,b;
 char name[30],sec[30];
 cout<<"Enter first String ";
 cin.getline(name,20);
 a.getString(name);
 cout<<"Enter Second String ";
 cin.getline(sec,30);
 b.getString(sec);
 a.display();
 b.display();
 String c;
 c = a+b;
 c.display();
 if((a==b)==0){
  cout<<"Same length\n";
 }
 else {
  cout<<"Different length\n";
 }
 return 0;
}

Expected Output

Enter first String Alok
Enter Second String Deepu
Alok
Deepu
AlokDeepu
Different length

Explanation of the Program

  • Here we are inventing entirely new semantic meanings for standard operators.
  • Instead of performing mathematical addition, our overloaded + operator concatenates strings. Instead of checking for exact value equality, our == operator only checks if the lengths of the two strings are equal.

Complexity

Time Complexity O(n) - Where n is the string length during strcat and strlen operations.
Space Complexity O(n) - To store the concatenated string result.
ADVERTISEMENT