Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was function overloading added to C++?

Tags:

c++

c

overloading

I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?

What went across the mind of the language designer at that time?

like image 547
CuriousGeek Avatar asked Nov 30 '10 13:11

CuriousGeek


People also ask

Why does C support overloading?

No, C doesn't support any form of overloading (unless you count the fact that the built-in operators are overloaded already, to be a form of overloading). printf works using a feature called varargs.

Why there is no function overloading in C?

Function overloading is a feature of Object Oriented programming languages like Java and C++. As we know, C is not an Object Oriented programming language. Therefore, C does not support function overloading.

Why do we need function overloading?

We use function overloading to save the memory space, consistency, and readability of our program. Function overloading shows the behavior of polymorphism that allows us to get different behavior, although there will be some link using the same name of the function.

Why do we use function overloading in C++?

C++ lets you specify more than one function of the same name in the same scope. These functions are called overloaded functions, or overloads. Overloaded functions enable you to supply different semantics for a function, depending on the types and number of its arguments.


1 Answers

It increases maintainability. If you have a type T and you call a function with it, then you need to change T, if the function has been overloaded for the new T then you can recompile instantly. In C you would have to go back and dig through all the call sites and change the function called. Take sqrt(). If you want to sqrt() a float, then you have to change to sqrtf().

Not just that, but the volume and complexity of C++'s type system is far more than in C, and having to have separate function names for every possible overload would quickly exhaust the reasonable pool of names for functions that serve the same purpose but take different arguments, because now there's a lot more arguments to take.

For example, compare the C and C++ string libraries. The C string library offers one method to append to a string - strcat(). C++'s std::string::append has eight overloads. What do you want to call them? append_a, append_b, etc? That's ridiculous- they all serve the same function, just in different ways.

Edit: It is actually worth mentioning that append is a really bad example, many of the C++ string overloads are very redundant. However, this is more general case than that and not all of those overloads redundant.

like image 126
Puppy Avatar answered Sep 24 '22 14:09

Puppy