Valhalla Legends Archive

Programming => General Programming => C/C++ Programming => Topic started by: GET_IN_MY_BELLY on January 04, 2004, 12:15 PM

Title: function overloading
Post by: GET_IN_MY_BELLY on January 04, 2004, 12:15 PM
why would you need this? can't you just put it all in the same thing? give me an example showing me that this can be useful for me.
Title: Re:function overloading
Post by: CupHead on January 04, 2004, 12:34 PM
It's useful when you have a function that needs to accept varying types of parameters, but don't want to create different functions for each data type.  For instance, an application might be in a packet buffer class where you want to add data.  Typically, you would need to do something like:


void PacketBuffer::InsertWORD(unsigned short Data)
{
 // ...
}

void PacketBuffer::InsertDWORD(unsigned long Data)
{
 // ...
}


With an implementation like:


PacketBuffer.InsertWORD (unsigned short)0x0001;
PacketBuffer.InsertDWORD (unsigned long)0x00000001;


With function overloading, you could do something like:

void PacketBuffer::Add(unsigned short Data)
{
 // ...
}

void PacketBuffer::Add(unsigned long Data)
{
 // ...
}


And then the implementation would be like:


PacketBuffer.Add (unsigned short)0x0001;
PacketBuffer.Add (unsigned long)0x00000001;


Basically it allows you to turn a common function with varying data types into a function able to be accessed with all data types rather than needing different function names for each data type you want to use.
Title: Re:function overloading
Post by: Arta on January 04, 2004, 12:36 PM
How about adding data to a packet?



void Add(DWORD Data)
{
 // Add a dword
}

void Add(WORD Data)
{
 // Add a word
}

void Add(LPSTR Data)
{
 // Add a string
}

// Now you can use the same function for adding DWORDs, WORDs, and strings:

DWORD d = 0;
WORD w = 1;

Add(d);
Add(w);
Add("abc");

Title: Re:function overloading
Post by: Adron on January 04, 2004, 06:18 PM
I like to make different versions, like Addw(short word), Addi(int integer), Adds(char *string), because that way I don't have to manually cast to add an int as a short.
Title: Re:function overloading
Post by: iago on January 04, 2004, 07:20 PM
I have overloaded + non-overloaded.   If I'm using a constant, I'll do addWord, addDWord, addByte, etc., and if I'm using variables I just use add().  It's really a matter of taste, though..