Program To Overload >= Operator To Compare Two Strings Using C++

LEVEL: Beginner

Whats in this post?

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


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

Background and Explanation of the code

The above program compare two string objects by overloading  ‘ >= ‘ operator having its declaration as

int operator >= (string);

This overloaded operator function takes one parameter of type string and returns an int type value.

In the main ( ), the statement

if (s1 >= s2)

on execution invokes the operator >= ( ) function through object s1 and object s2 is passed as argument.Overloaded operator function compares the data members of s1 and s2 objects using library function strcmp ( ).Here the strings are compared in alphabetic order.


Enter string s2 =  rahul

Alphabetically s1 is greater than ( or equal to ) s2