Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this program hang?

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?

like image 830
big-z Avatar asked Dec 09 '22 15:12

big-z


1 Answers

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.

like image 157
Igor Zevaka Avatar answered Feb 23 '23 16:02

Igor Zevaka