How to overload a function in c ++ without changing its signature? Asked the question at the interview, it has now become interesting how this is possible. Thanks for attention.

  • 2
    If you are asked such questions at the interview, do not go to work there. They are interested not in the ability to program, but in knowledge of strange tricks and distant dusty corners of the language standard. Look for a company where they will be asked to write code at the interview. - VladD

1 answer 1

If the syngatur does not change, then there is no overload. This is logical. But there are two options that questioners could come up with.

1) if the function is placed in another namespace. Then it will be possible to call different versions.

void k(int x); namespace my { void k(int x); } ::k(1); // вызов первой my::k(2); // вызов второй. 

And of course, you can add using namespace my; and voila :)

2) the second method is that there are no methods in c ++. More precisely, they are, but are called class functions. And since these are functions, you can make the class a successor and reload it. The signature will not change. But it was necessary to clarify what function they thought.

UPD New, tricky way

Let him have a function

 int func(int k, int m) { .... } 

And it is necessary that an overloaded version be called up in a new place. To do this, first write the implementation of this new version

 int new_func(int k, int m) { .... } 

And when you need to call, we write

 #define my_func(a, b) func(a, b) 

and an example call

 func (1,1); // старая версия #define func(a,b) my_func(a,b) func(1,1); // новая версия, то есть по факту my_func #undef func func (1,1); // и снова старая 

Yes, this method requires "manual selection", but from the outside it looks quite like an overload.

  • I asked about the scope of the f-th, and they told me that they were in one area, I answered right away that it was impossible, but they told me that they could, but think like that ( - fortunado
  • then the second option. but there is another way, grandfather. called macros. now update the answer. - KoVadim
  • one
    Maybe they meant const at the end of the method declaration. - igumnov
  • Thank you, I hope that there is no other super-tricky way. - fortunado
  • It seems to me that technically a macro trick is not considered an overload. I think they meant the definition of a method (or function, as you like) in a class with the same signature as in the parent class, if it is not virtual. Although who knows them. - VladD