• Welcome to Valhalla Legends Archive.
 

function overloading

Started by GET_IN_MY_BELLY, January 04, 2004, 12:15 PM

Previous topic - Next topic

GET_IN_MY_BELLY

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.

CupHead

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.

Arta

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");


Adron

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.

iago

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..
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*