简体   繁体   中英

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?

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.

void my_func( char value ) { my_func(value); }

You're passing the value which is char so it resolves to calling the same method with accepts a char parameter. It becomes an endless loop.

void my_func( char value ) { my_func(value); }

right there, you've written a recursive function with no base case. I don't know too much about C++, but you need to somehow specify that you want to call X's my_func, not X2's(I'm assuming that's what you want to do.)

edit: To fix it, you need to cast value to an int

The program gets in an infinite loop. my_func() calls itself and there's no condition to exit out of it.

Your call my_func(value) is recursive. Did you mean super::my_func(value) ?

You need to explicitly call the base class' function, ie:

struct X
{
  void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};

struct X2 : X
{
  void my_func( char value ) { X:my_func(value); }
};

By default, the compiler uses functions within the same class if present, as there is no way for it to know which one you actually want to use. By specifying BaseClass::Function within a derived class' method, the compiler will explicitly create a call to that base class's method, even if you have overridden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM