Login | Register   
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


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

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