I have the following code which is seems to be lead to the infinite loop:
struct X
{
void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};
struct X2 : X
{
void my_func( char value ) { my_func(value); }
};
What is the problem with it?
The second bit is infinitely recursive:
struct X2 : X
{
void my_func( char value ) { my_func(value); } //calls itself over and over again
};
Prefix my_func
with the name of the base class and you will be OK
struct X2 : X
{
void my_func( char value ) { X::my_func(value); }
};
EDIT Just realised that base class my_func
's signature is different. C++ compiler resolves the function overload statically, that means it will pick the function that best matches the type of the argument, that's why it calls the char
overload.
For example:
char cChar = 'a';
myfunc(cChar);
void myfunc(char a){} //<-- this one is called
void myfunc(int a){}
int iInt = 1;
myfunc(iInt);
void myfunc(char a){}
void myfunc(int a){} //<-- this one is called
Thanks Charles Bailey. The above code does not apply in this case as X2
's my_func
hides base class's my_func
. This leaves the only solution to qualify the function with the class name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With