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;    ...    };}

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: