Thursday, 12 May 2016

Operator overloading in c++

A small example of how to overload operators in c++. In this program we have binary operator, relation operator, stream operator used on String class. Constructor are also use to directly assign string to class.

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

class String
{
 char s[50];
public:
 String()
 {
   strcpy(s,NULL);
 }

 String(char *v)
 {
  strcpy(s,v);
 }

 String(String& v)
 {
  strcpy(s,v.s);
 }

 String operator +=(String a){
   return String(strcat(s,a.s));
 }

 int operator ==(String a)
 {
     return !strcmp(s,a.s);
 }

 int operator !=(String a)
 {
     return strcmp(s,a.s);
 }

 int operator >(String a)
 {
     return strcmp(s,a.s);
 }

  int operator <(String a)
 {
     return strcmp(s,a.s);
 }

  String operator =(String b){
   return String(strcpy(s,b.s));
 }

  String operator +(String b){
    String s1(s);
   return String(strcat(s1.s,b.s));
 }

  friend ostream &operator<<(ostream &, String );
  friend istream &operator>>(istream &, String &);
};

ostream &operator<<(ostream &os, String ob)
{
 os << ob.s;
 return os;
}

istream &operator>>(istream &is, String &ob)
{
 is>>ob.s;
 return is;
}

void main()
{

 String obj("Hello C ");
 String obj1("Hello C++ ");
 if(obj1>obj)
 cout<<obj1<<" is greater than "<<obj;
else if(obj1<obj)
     cout<<obj1<<" is less than "<<obj;
 else
     cout<<"Both "<<obj1<<" and "<<obj<<" are equal";
 return;
}
#cprogramming #clanguage #c++

No comments: