devxlogo

Overloading Methods

Overloading Methods

Suppose you are writing a method in a class that accepts a parameter of a given type. Such a method can also be called with an argument of a different type?as long as an implicit conversion exists between the two types (for example, short to int).

 class example{public:    void method(int parameter);    ...}int main(){	example eg;	short pants = 42;	eg.method(pants); // short to int conversion here	...	return 0;}


It is possible to overload such methods, and by making the overloaded method private, unwanted conversions can be turned into compile time errors. For example:

 class example{public:    void method(int parameter);    ..private: // reject unwanted conversions     void method(short);    ...}int main(){	example eg;	short pants = 42;	eg.method(pants); // Compile time error	...	return 0;}


You can even use this technique to overload on different signedness of integers. For example:

 namespace non_std{    class string    {    public:              char & operator[](size_t index);        const char & operator[](size_t index) const;    ..    private: // reject unwanted conversions         void operator[](signed int);        void operator[](signed int) const;    ...    };}

See also  How IoT Tech Will Transform Logistics
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist