PoundXI
PoundXI

Reputation: 121

calling same name function

Is it possible to call foo() function from Foo.cpp without changing function name Foo::foo() to Foo::newfoo().

main.cpp

#include <iostream>
#include "Foo.hpp"

class Foo {
public:
    void foo() {
        std::cout << "Foo::foo\n";
    }
    void bar() {
        std::cout << "Foo::bar\n";
        foo();// need to call foo() function from foo.cpp not Foo::foo()
    }
};

int main () {
    Foo f;
    f.bar();
    return 0;
}

Foo.hpp

#ifndef FOO_HPP_INCLUDED
#define FOO_HPP_INCLUDED

void foo();

#endif // FOO_HPP_INCLUDED

Foo.cpp

#include "Foo.hpp"
#include <iostream>
void foo(){
    std::cout << "foo\n";
}

ps.sorry for my poor english.

Upvotes: 9

Views: 5865

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

If the free function foo is defined in some namespace xyz, then do this:

 xyz::foo();  //if foo is defined in xyz namespace

or else just do this:

::foo();     //if foo is defined in the global namespace

This one assumes foo is defined in the global namespace.

It is better to use namespace for your implementation. Avoid polluting the global namespace.

Upvotes: 2

Alok Save
Alok Save

Reputation: 206526

Use fully qualified name of the free function.

::foo();

The :: in front of the function name, tells the compiler to call the function by the name foo() that is in the global scope.
If the free function foo() was in some other namespace you need to use fully qualified name specifying the namespace.

namespacename::foo();

Upvotes: 17

Related Questions