Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the unsuitable overloaded function is called?

Why does the following code always prints "type is double"? (I have seen this code in StackOverflow)

#include <iostream>


void show_type(...) {
    std::cout << "type is not double\n";
}

void show_type(double value) { 
    std::cout << "type is double\n"; 
}

int main() { 
    int x = 10;
    double y = 10.3;

    show_type(x);
    show_type(10);
    show_type(10.3);
    show_type(y);


    return 0;
}
like image 504
A. Mashreghi Avatar asked Jan 07 '23 05:01

A. Mashreghi


2 Answers

http://en.cppreference.com/w/cpp/language/overload_resolution says:

A standard conversion sequence is always better than a user-defined conversion sequence or an ellipsis conversion sequence.

like image 160
Christian Hackl Avatar answered Jan 09 '23 18:01

Christian Hackl


   void show_type(double value) { 
        std::cout << "type is double\n"; 
    }

if u comment above line then output will be

type is not double
type is not double
type is not double
type is not double

it means that compile always prefer the void show_type(double value) over void show_type(...).

in your case if you want call the method void show_type(...) pass the two or more arguments when u calling this method show_type(firstParameter,secondParameter)

#include <iostream>


void show_type(...) {
    std::cout << "type is not double\n";
}

void show_type(double value) { 
    std::cout << "type is double\n"; 
}

int main() { 
    int x = 10;
    double y = 10.3;

    show_type(x);
    show_type(10);
    show_type(10.3);
    show_type(y);
    show_type(4.0,5); //will called this  method show-type(...) 


    return 0;
}

now the output of above line will be

type is  double
type is  double
type is  double
type is  double
type is not double  //notice the output here

more info on var-args

like image 40
Roushan Avatar answered Jan 09 '23 18:01

Roushan