Click here to Skip to main content
13,353,294 members (54,133 online)
Click here to Skip to main content
Add your own
alternative version


10 bookmarked
Posted 23 Oct 2010

Binary +, Implicit and Explicit Operator Overloading

, 23 Oct 2010
Rate this:
Please Sign up or sign in to vote.
How Can you Overload an Binary +, Implicit and Explicit conversion Operators

What is Operator Overloading?

We know that standard data types supplied by languages are well known and there will be operators like +,* ,% that operate on these data types. But, what is the case if it is user-defined types say a 3dpoint class, which is the combination of three integers. Well, all languages that supports operator overloading says, “It is your Type. Please you say how the operator + should work”.

If you say “How the Operator + should work for 3point class”, then you are overloading the + operator. Because, it will now know how to add two integer and how to add two 3dpoint.

Below are the types of overloading that I will demonstrate in this article:

  • Implicit Conversion Operator
  • Explicit Conversion Operator
  • Binary Operator

Let us start with TimeHHMMSS Class

Before we move on to the Overloading, first let me explain what this class will do. The class is used to store the time in Hour, Minute and Seconds. There are three members defined for that. The class looks like:

class TimeHHMMSS
	//001: Parts of the time class
	public int m_hour;
	public int m_minute;
	public int m_sec;

The default constructor will set all the members to zero. And a overloaded version will accept hour, minute and seconds. Below is the code for Constructors:

//002: Default constructor for the class
public TimeHHMMSS()
	m_hour = 0;
	m_minute = 0;
	m_sec = 0;

//003: Overloaded Constructor
public TimeHHMMSS(int hr, int min, int sec)
	m_hour = hr;
	m_minute = min;
	m_sec = sec;

All classes in C# have Object as their base class. We will override the ToString method our own way.

//004: Every class that we create has Object as the base class. Override the ToString
public override string ToString()
	return string.Format("{0}:{1}:{2}", m_hour, m_minute, m_sec);

Implicit Conversion – (A) Integer to TimeHHMMSS

Below is the syntax for Implicit conversion:
public static implicit operator <convert>(<convertfrom> Variable) </convertfrom></convert>

We will get the integer as parameter. So the time is specified in smaller units, say in seconds passed as an integer parameter. 1 Hour, 10 minutes, 15 Seconds can be specified in seconds as 4215. These “seconds” taken as an integer parameter is processed to split into Hour, Minutes, and Seconds. After the Split, we have all the member variables of the class ready to return back. Below is the Conversion operator:

//005: Implicit Conversion Operator. Conversion from int to TimeHHMMSS
public static implicit operator TimeHHMMSS(int totalSeconds)
	//005_1 : Declarations
	int hour, min, seconds;
	int RemainingSeconds;
	TimeHHMMSS returnobject = new TimeHHMMSS();

	//005_2: Calculate Seconds
	seconds = totalSeconds % 60;
	returnobject.m_sec = seconds;

	//005_3: Calculate Minutes
	RemainingSeconds = totalSeconds - seconds;
	min = RemainingSeconds % ( 60 * 60 ); //Calculated minutes in terms of seconds
	returnobject.m_minute = min / 60 ;

	//005_4: Calculate Hours
    	RemainingSeconds =  totalSeconds - 
		( returnobject.m_minute * 60 + returnobject.m_sec );
	hour = RemainingSeconds % (60 * 60 * 24 ); // Hour in Seconds
	returnobject.m_hour = hour / 3600;

	return returnobject;

OK, how is the above operator used? If we assume t2 is the TimeHHMMSS object constructed using the default constructor, the below statement will invoke the overloaded implicit conversion t2 = 33175;

Implicit Conversion – (B) TimeHHMMSS to Integer

Now, we will implement the same implicit conversion in the reverse; that is, we will make conversion from Time Object to integer. I hope as looked at the previous function, you will know what the implementation is. Below is the function:

//006: Implicit Conversion Operator. Conversion from TimeHHMMSS to integer
public static implicit operator int(TimeHHMMSS time)
	return (time.m_hour * 60 * 60) + (time.m_minute * 60 ) + time.m_sec ;

When will the calling code invoke the above implicit conversion? The code is below:

int timeinSeconds;
timeinSeconds = t2;

Explicit Conversion- Conversion from Float to TimeHHMMSS

In the above conversion, we saw that the conversion takes place even we do not explicitly specify that. The way we implement the Time class is we recommend integer data type, so we make the conversion for integer implicit. For a float data type, we will implement (not actually an implementation, we will handle if a user accidentally makes a float conversion explicitly, and re-direct to int implicit conversion).

Below is the code that will take a float, re-directs to integer implicit conversion. From the client point of view, it is an explicit conversion:

//007: Explicit Conversion Operator. Conversion from float to TimeHHMMSS.
public static explicit operator TimeHHMMSS(float totalSeconds) // We don't want 
			//to handle fraction in Seconds (Micro Sec or nano Sec stc)
	TimeHHMMSS returnobject = new TimeHHMMSS();
	returnobject = (int) totalSeconds; 	//Makes a call to implicit conversion : 
	return returnobject;

Below is the piece of client code which will make a call to our explicit overloaded operator:

TimeHHMMSS t3 = (TimeHHMMSS) 23213.67f;

Binary Operator Overloading – Overload + Operator

Now, it is time to overload the binary operator +. With this, we can add two TimeHHMMSS class and get back the added TimeHHMMSS.

The call will write statement something like the one below:
TimeHHMMSS t4 = t1 + t2;

Our + overloading function will take TimeHHMMSS t1, t2 as two parameters in the same order; that is t1 as first parameter and t2 as second parameter. Then, the added TimeHHMMSS is returned back to the t4 object of the same type. We will use the implicit Time->Integer conversion on t1 and t2. Add the integer values then return the added value. Since the return type we specify as TimeHHMMSS, once again an implicit conversion in reverse direction takes place; that's a conversion from integer->TimeHHMMSS. The overloaded + operator is shown below:

//008: Operator Overloading +. Binary Operator.
public static TimeHHMMSS operator+ (TimeHHMMSS operandLH, TimeHHMMSS OperandRH)
	//008_1: Get the Seconds and Add. 
	int totalSeconds, LHS_Seconds, RHS_Seconds;
	LHS_Seconds = operandLH;		//Implicit conversion: Time -> int
	RHS_Seconds = OperandRH;		//Implicit conversion: Time -> int
	totalSeconds = LHS_Seconds + RHS_Seconds;

	//008_2:	Return the Seconds. Required return type is TimeHHMMSS, 
	//			what we return is integer. 
         // Again one more implicit conversion in reverse
	return totalSeconds; //Implicit conversion: int -> Time

Closing Notes

  1. The binary operator will work for the following statements also:
    t4 = t4 + 4215;
    t4 = t4 + (TimeHHMMSS) 54321.456f ;

    Debug to see what kind of conversion takes place.

  2. If you overload an == operator, then you should overload !=. Same holds for operator like < and >, etc.


003_Exe: Run it in the console to see the output. Below is the code that will use the TimeHHMMSS.

static void Main(string[] args)
	//Usage_000: Create the Time Class
	TimeHHMMSS t1 = new TimeHHMMSS(0,20,10);
	Console.WriteLine("The time is: {0}", t1.ToString());

	//Usage_001: Implicit Conversion Operator[ int to Time ]
	TimeHHMMSS t2 = new TimeHHMMSS();
	t2 = 33175;		//=> Implicit conversion for int to Time Takes place
	Console.WriteLine("The time is: {0}", t2.ToString());

	//Usage_002: Implicit  conversion Operator[ Time to int ]
	int timeinSeconds;
	timeinSeconds = t2;		//=> Implicit conversion from Time to Integer
					// Takes place
	Console.WriteLine("The time {0} in Seconds (2)", t2.ToString(),timeinSeconds );

	//Usage_003: Explicit Conversion Operator. 
         //[Here I am asking convert my float to an Time Object]
	TimeHHMMSS t3 = (TimeHHMMSS) 23213.67f; 
	Console.WriteLine("The time is: {0}", t2.ToString());

	//Usage_004_A: Overloaded + operator. 
         //[ Put a Break point here & Step-in. 
         //You will learn more]
	// [Tag1]  a) Time->int implicit for t1, t2. b) add two int c)
         //return added int. int->Time implicit
	TimeHHMMSS t4 = t1 + t2;
	Console.WriteLine("The time is: {0}", t4.ToString());

	//[Tag2] a) int->Time Conversion. Read the Comment [Tag1]
         t4 = t4 + 4215; 
	Console.WriteLine("The time is: {0}", t4.ToString());

	//a)Float->Time Conversion. Explicit. [Read Tag2] 
	t4 = t4 + (TimeHHMMSS) 54321.456f ; 

003_Src: Project source code written in .NET 2003 IDE. Convert the project for later version. When prompted by (IDE 2005 or later), click yes. Put a break point static void main, and examine the code with informative comments.

Hope you like this article.


  • 23rd October, 2010: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sivaraman Dhamodharan
Software Developer iSOFT
India India
I am working as software engineer in iSOFT R&D. I have been come across C++,MFC, .net technologies. I do like playing video games, reading books.


You may also be interested in...

Comments and Discussions

Generalnice Pin
Pranay Rana22-Dec-10 2:31
memberPranay Rana22-Dec-10 2:31 
GeneralNicely done Pin
CIDev22-Nov-10 15:24
memberCIDev22-Nov-10 15:24 
GeneralMy vote of 5 Pin
Peter Molnar26-Oct-10 6:01
memberPeter Molnar26-Oct-10 6:01 
GeneralRe: My vote of 5 Pin
sirama200427-Oct-10 2:30
membersirama200427-Oct-10 2:30 
GeneralMy vote of 4 Pin
DaveyM6925-Oct-10 13:24
mvpDaveyM6925-Oct-10 13:24 
GeneralRe: My vote of 4 Pin
sirama200425-Oct-10 17:38
membersirama200425-Oct-10 17:38 
GeneralA Suggestion about Time Calculations Pin
The Manoj Kumar23-Oct-10 10:34
memberThe Manoj Kumar23-Oct-10 10:34 
GeneralRe: A Suggestion about Time Calculations Pin
sirama200423-Oct-10 17:47
membersirama200423-Oct-10 17:47 
GeneralRe: A Suggestion about Time Calculations Pin
HaBiX25-Oct-10 1:39
memberHaBiX25-Oct-10 1:39 
GeneralRe: A Suggestion about Time Calculations Pin
sirama200425-Oct-10 2:48
membersirama200425-Oct-10 2:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180111.1 | Last Updated 23 Oct 2010
Article Copyright 2010 by Sivaraman Dhamodharan
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid