-4

Following is my scenario:

file.h This file contains two function with extern

extern int add(int a, int b);
extern int sub(int a, int b);

file.cpp Implementation of above functions.

int add(int a, int b)
{
    return 20;
}

int sun(int a, int b)
{
    return 20;
}

test.h This is class test in which two member function with same signature as extern add and sub in file.h

class test
{
    public:
          test();
          ~test();
    private:
         int add(int a, int b);
         int sub(int a, int b);
}

test.cpp Implementation of test class in test class constructor add function is called as well as both file are included.

#include "test.h"
#include "file.h" // Contains extern methods
#include <iostream>

test::test()
{
     int addition = add(10, 10);
     printf("Addition: %d ", addition );
}

int 
test::add(int a, int b)
{
    return 10;
}

int 
test::sub(int a, int b)
{
    return 10;
}

main.cpp

 #include "test.h"
 int main()
 {
   test *a = new test();
 }

Now my question is in main class what will be printed. Whether it will print

it giving output as Addition : 10 Why it is giving 10 ? Is class test uses its own function add() and sub(). Because both function are present in file.h and same class. My guess was it will give ambiguity for functions. Is there any standard if so please explain. And how can i use functions from file.h in class test.

DigviJay Patil
  • 986
  • 14
  • 31

2 Answers2

1

Calling add inside the test class will use the add member function.

To call the global add function use the global scope resolution operator :::

int addition = ::add(10, 10);
Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

use can also do it using namespace. in file.h

#include "file.h"
namespace file
{
     int add(int a, int b)
     {
         return 20;
     }

     int sub(int a, int b)
     {
         return 20;
     }
}

in test.cpp

#include "test.h"
#include "file.h" 
#include <iostream>

test::test()
{
     int addition = file::add(10, 10); // used namespace here
     printf("Addition: %d ", addition );
}

int 
test::add(int a, int b)
{
    return 10;
}

int 
test::sub(int a, int b)
{
    return 10;
}
PatilUdayV
  • 597
  • 1
  • 4
  • 8