views:

207

answers:

7

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?

+10  A: 
Igor Zevaka
Thanx. I thought that `my_func` is not defined at that point yet and `X::my_func` should be called.
big-z
@zilgo: It isn't defined, but it is declared. And that's all you need.
GMan
In a derived class any function with the same name but a different signature will hide the base class functions of the same name. This means that in `X2`'s member functions unqualified `my_func` _always_ refers to `X2::my_func` and never to `X::my_func`. There is no "best match" going on here. The posted "For example:" is misleading as it simply doesn't apply in this case.
Charles Bailey
@Charles Bailey. Thanks. Corrected.
Igor Zevaka
+2  A: 
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.

Developer Art
+2  A: 
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

Bwmat
A cast to `int` of the parameter isn't going to help. `my_func` in the derived class hides the base class `my_func`. An explicit qualification of `my_func` is needed.
Charles Bailey
Doesn't it overload it, not hide it?
Bwmat
A: 

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

Khnle
A: 

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

Eyal Schneider
A: 

The issue occurs due to hiding. http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9

Raam
A: 

You need to explicitly call the base class' function, i.e.:

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.

Mephane