Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
PoundXI Avatar asked May 27 '12 06:05

PoundXI


2 Answers

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();
like image 143
Alok Save Avatar answered Sep 18 '22 20:09

Alok Save


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.

like image 26
Nawaz Avatar answered Sep 17 '22 20:09

Nawaz