Sign in to follow this  
Polar Productions

Overloading Functions

Recommended Posts

Hello all. This is my first post here. I also do not know a whole lot about c++ but I know enough to get me through console apps. One thing I wondered though, is how people feel about overloading their functions? I personally dont think it would be a very good practice however in certain circumstances it might be more suited to the situation. So I would like the opinions of people more advanced than myself.

Share this post


Link to post
Share on other sites
I think it's perfectly fine. I must admit, it does create complexity, which in turn can lead to confusion. But, look at this situation: You have a string class with 3 constructors: a default, one for initializing and copying a C string, and one initializing and copying another string class. How else would you go about this? And then say you have a templated function that creates a string class. It's not perfectly safe, but because you can't know ahead of time, function overloading works great in this situation.

Share this post


Link to post
Share on other sites
In some cases, you can overload operators to perform what you think would be logical functionaly but would normally not be provided, thus reducing complexity overall. For example, if you were implementing a vector class, its much more intuitive to simply overload the +/- operators to add/subtract vectors, so you could do this:
vec3 = vec1 + vec2;
rather than:
vec3 = addVectors(vec1, vec2);

Share this post


Link to post
Share on other sites
Overloaded functions are useful when you want to do essentialy the same thing with different data types. Though I think in a lot of cases this can be avoided by using template functions, conversions and default arguments. It's extremely useful when overloading operators though.

Share this post


Link to post
Share on other sites
Essentially what BringBackFuturama said. I would also point out that in any non-trivial program, ctors are overloaded (necessarily) all the time. Function overloading is also convenient for compile-time dispatch, where, using the same name, multiple functions can be called based on a type (or trait). In this case, templates do not provide a solution, and in fact are often overloaded themselves (look inside your standard library headers sometime for some examples).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this