AngryDuck AngryDuck - 1 year ago 150
C++ Question

Overload a method or use default values? c++

I'm still relatively new to C++ and I can't seem to figure out the difference in the following two ways of coding a function that may take one parameter or maybe two or three or more. Anyway, here's my point

function overload:

int aClass::doSomething(int required)
{
//DO SOMETHING
}

int aClass::doSomething(int required, int optional)
{
//DO SOMETHING
}


how is this different to, default value:

int aClass::doSomething(int required, int optional = 0)
{
//DO SOMETHING
}


I know in different circumstances one may be more suitable than another but what kinds of things should I be aware of when choosing between each of these options?

Answer Source

First off, you're talking about overloading, not overriding. Overriding is done for virtual functions in a derived class. Overloading refers to the same function name with a different signature.

The difference is logical - in the first case (2 versions), the two functions can behave completely different, whereas the second case will have more or less the same logic. It's really up to you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download