What is function overloading in D?
Overview
An overloaded function is a repeated declaration with the same scope, but a different argument and definition. When an overloaded function is called in D, the compiler defines the function by comparing the argument types and the parameter types specified. The process of doing this is called overload resolution.
Function overloading
For function overloading, the argument names and types must be different for the same function in the same scope. The overloaded function cannot differ only by the return type.
Code example
import std.stdio;import std.string;class printData {public:void print(int n) {writeln("data type is an int: ",n);}void print(double l) {writeln("data type is a float: ",l );}void print(string m) {writeln("data type is a string: ",m);}};void main() {printData pd = new printData();// Call `print` to print the integerpd.print(5);// Call `print` to print the floatpd.print(500.263);// Call `print` to print the characterpd.print("Hello D");}
Function overloading in D
Explanation
- Line 4: We declare a class
printData.
- Lines 6 to 8: We create a function for printing, and pass in an
integerdata type as its parameter. (We do the same thing from lines 10 to 12 and lines 14 to 16, but their cases have different data types passed in as parameters.)
- Line 20: We create a new instance of the initial class we created.
- Lines 23 to 29: We then access the
printfunction using different data types.