dcsimg
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: Intermediate
Oct 31, 2000

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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;
    ...
    };
}
Jon Jagger
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date