I just wanted to know What are the factors decisive in making a function call during
overloading. As I know its the signature of parameters, number of parameters passed
Which plays an important role. But is there the const part also Which plays an important
part in overloading or not. Overloading of 1st and 2nd function works fine but if a add
a third function with const as a characteristic in passed parameters, I get compilation error. int A::sum(int, int) and int A::sum(int, int) cannot be overloaded. Just giving the code snippet for class:
class A
{
private:
int x;
int y;
public:
int sum ( int a, int b )
{
cout << " Inside 1st ";
return (a+b) ;
}
int sum (int a ,int b) const
{
cout << " Inside 2nd ";
return (a+b) ;
}
int sum (const int a ,const int b)
{
cout << " Inside 3rd ";
return (a+b) ;
}
A(){x=0;y=0;}
~A(){};
};
When I declare the normal object and make a call to sum the first function gets called and in case of a const object second sum is being called. That’s perfectly fine. But if I write 1st and 3rd function both it becomes an issue. Why so?
You can overload on
const-ness, but only where it actually makes a difference. What do I mean “actually makes a difference”? Well, if you declarethe
constmatters: you are saying that one overload offooguarantees not to modify the memory thatptrpoints to, and the other doesn’t. But if you declarethe
constdoesn’t matter: scalar arguments are always passed by value, so neither hypothetical variation offoocan modify the value ofxin its caller, even if it wanted to. Therefore, the C++ standard says that theconstis discarded, and these are two different declarations of the same function, one of which is erroneous.The position of the
constrelative to the*matters. A pointer is itself a scalar, so these are also two declarations of the same function:because here the
constqualifies the pointer itself rather than the object it points to.That brings us to methods: a
constqualifier after the argument list on a method declaration applies to the object pointed to bythis, and that can be overloaded on:You should think of these declarations as being rewritten internally to:
and then everything works according to the normal rules for overloaded functions.