Ritesh Kumar Gupta
Ritesh Kumar Gupta

Reputation: 5191

Overriding function from caller source file in C++

There is a c++ file called main.cpp.

main.cpp

#include "addition.h"
#include <iostream>
int main(){
   int x=2;
   int y=3;
   std::cout<<getsum(x,y);
}

This file includes custom header file called addition.h

addition.h

#include "my_adders.h"
namespace{
int getsum(int a,int b){
    return calculate_addition_h(a,b);
}
}

my_adders.h

#include <maths.h>
int calculate_addition_h(int p, int q){

      int sum=0;
      //Fn definitions
      return sum;
}

In main.cpp, i need to override the definition of calculate_addition_h function.

Is it possible?

I tried copying calculate_addition_h definition as well as declaration in main.cpp. However, when, i printed the o/p, calculate_addition_h method in my_adders.h was invoked, not the one in main.cpp.

Please note: I cannot make any changes to addition.h or my_adders.h.

Any help is appreciated!

Upvotes: 2

Views: 522

Answers (2)

gwiazdorrr
gwiazdorrr

Reputation: 6349

Turns out it is possible without altering any of the headers and preprocessor magic!

Since your getsum is in an unnamed namespace, you can define calculate_addition_h function in the unnamed namespace before including addition.h:

main.cpp

namespace
{
    int calculate_addition_h(int p, int q)
    {
        return 666;
    }
}

#include "addition.h"
#include <iostream>
int main(){
    int x=2;
    int y=3;
    std::cout<<getsum(x,y);
}

In C++, functions in same namespace take precedence over functions in parent namespaces. In this case parent namespace is the global one.

Upvotes: 2

rajenpandit
rajenpandit

Reputation: 1361

As you are using global function, so it is not possible to override the function as it can be done in class. Its better to define a new function with the same name inside a different namespace

Upvotes: 0

Related Questions