If I create a function that has the same name and arguments as another function,but a different return type,is it still called overloading?
Is it still called overloading?
GDNet+ - Reputation: 8807
Posted 20 June 2013 - 11:52 AM
Yep, you can't do that -- the compiler has no good way of knowing which function you intended to call without any difference in arguments. The work around would be to append "AsInt", "AsDouble" or somesuch to the end of your function name. Another option would be to create the function as a template function, throw a static assert in the generic function body, and then specialize the template function on the return types you want to support -- then you call the function like foo<int>(arg1, arg2).
Crossbones+ - Reputation: 4249
Posted 20 June 2013 - 12:02 PM
C# also supports this when a class inherits from interfaces that have the same methods (e.g. IEnumerator GetEnumerator() and IEnumerator<T> GetEnumerator(), when something inherits from IEnumerable and IEnumerable<T>) . You have to cast to go through the interface before you make the method call.
Edited by phil_t, 20 June 2013 - 01:07 PM.
Members - Reputation: 789
Posted 20 June 2013 - 12:54 PM
They can in C++ when derived class member functions overriding base class member functions with covariant return types. I believe Java introduced covariant return types a while ago, but I don't remember with which version.
That's what i'm reffering to.
So is it still called overloading?
Moderators - Reputation: 8727
Posted 20 June 2013 - 01:11 PM
In that case, it has nothing to do with the return type, or even the parameters for the matter. Just having a function in a derived class with the same name as one or more functions in the base class is enough to override the functions in the base class.
Moderators - Reputation: 9730
Posted 20 June 2013 - 01:25 PM
Members - Reputation: 789
Posted 20 June 2013 - 01:39 PM
Yes and no. Covariant return types are a special case when overriding virtual functions. In that case even though the return type differs, it still is an override of the base virtual function. It's not exactly the same as regular overrides.
What do you mean with regular overrides? Isn't overriding a term used just for giving another definition for a virtual function?
Crossbones+ - Reputation: 3308
Posted 20 June 2013 - 10:48 PM
Yes, it is. But since we're talking about "covariant-return-type overrides", it makes sense to talk about overrides whose return type is exactly as originally specified, and that would be the regular override, an override like it always used to be.
Isn't overriding a term used just for giving another definition for a virtual function?