Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Avoid Overriding method from library

I want to have the same name has the method from the C++ library cmath in a class method but without overriding it by my own method. I know I could just change the name but that is not what I want to do. Is this possible ?

calculator.cpp:

#include <calculator.h>
#include <cmath>

int Calculator::pow(int entier, int puissance) {
     return pow(entier, puissance);
}

calculator.h:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Calculator {
public:
      Calculator() {}
      int pow (int a, int b);
};

I already know that the types I am using are wrong for this type of computation but that is not the point.

>Solution :

You are not overriding anything. Your pow function is in a different scope than std::pow (or the global ::pow). The standard library pow is still there, unchanged by your definition.

It is just that unqualified name lookup will only find the functions with the name declared in the inner-most scope where a declaration for the name is found.

If that is not what you want, you need to qualify then name to let the compiler know which pow exactly you want to call, e.g.

 return std::pow(entier, puissance);

to call the pow function in the standard library namespace std or

 return ::pow(entier, puissance);

to call the pow function in the global namespace scope. However, including <cmath> does not guarantee that the standard library pow function will be declared in the global namespace scope, which is why you should use std::pow (instead of ::pow or just pow) in any case anyway.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading