calling same name function - c++

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.

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();

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.

Related

How to friend a function inside a namespace which is in a different file?

I'm having an issue with a friend function.
Basically I have a class in a header (inside a namespace), which contains a friend function:
namespace X {
class Foo {
// private members
friend void SomeNamespace::someFunction(const Foo& foo);
}
And in a separate header, I have the function which I'm trying to make a friend, which is inside a namespace:
#include "classHeader.h"
namespace SomeNamespace {
void someFunction(const X::Foo& foo);
}
This doesn't seem to work, as someFunction can't access Foo's private members, apparently.
After some research I found out that I was missing a forward declaration, so I tried adding it:
namespace X{class Foo}; // Forward declare class
void SomeFunction(const X::Foo& foo);
But this does not seem to work either. What's wrong?
To expand on my comments, lets say you have the following three files:
Foo header file
#include "SomeNamespace.h"
namespace X
{
class Foo
{
friend void SomeNamespace::SomeFunction(const Foo&);
};
}
SomeNamespace header file
namespace X
{
// Forward declaration
class Foo;
}
namespace SomeNamespace
{
void SomeFunction(const Foo&);
}
SomeNamespace source file
#include "SomeNamespace.h"
#include "Foo.h"
void SomeNamespace::SomeFunction(const Foo& foo)
{
}
[Note: Things like actual contents, as well as header include guards, purposefully omitted for brevity]
One of the header files needs to use forward declaration only, while the other can use #include.
The important part is that you must include all needed header files in the source file where you define (implement) the classes and functions.
Here's one way:
s.hpp
#pragma once
class Foo; // forward declaration is enough here since you only use a reference
namespace SomeNamespace {
void someFunction(const Foo& foo);
}
f.hpp
#pragma once
#include "s.hpp" // the function declaration of someFunction is needed
class Foo {
public:
Foo(int X);
friend void SomeNamespace::someFunction(const Foo& foo);
private:
int x;
};
s.cpp
#include "f.hpp" // Foo's definition is needed here
#include "s.hpp"
#include <iostream>
namespace SomeNamespace {
void someFunction(const Foo& foo) {
std::cout << foo.x << '\n'; // private member now accessible
}
}
f.cpp
#include "f.hpp"
Foo::Foo(int X) : x(X) {}

Loading external class c++

I am trying to load a class defined in a .dll file. However there are two slightly different ways of defining the class in the dll. I'm not sure which is the more legit way to do it, and I don't know why the second way also works. Here is a simple example:
Method 1:
In main.cpp:
#include <iostream>
#include <windows.h>
#include <memory>
#include "bar.h"
using namespace std;
typedef bar* (* MYDLLPROC)();
int main()
{
unique_ptr<bar> theresult;
auto thelib = LoadLibrary(TEXT("foo.dll"));
if (thelib != NULL) {
MYDLLPROC theprocs = (MYDLLPROC)GetProcAddress(thelib, "Myfoo");
cout << "load successfully" << endl;
theresult.reset(theprocs());
theresult->printmsg();
} else {
cout << "cannot load the dll" << endl;
}
return 1;
}
The bar is defined as a pure virtual class in bar.h:
class bar {
public:
virtual ~bar() {};
virtual void printmsg() = 0;
};
In the foo.dll source file:
#include <iostream>
#include <windows.h>
#include "bar.h"
using namespace std;
class foo: public bar {
public:
foo() { cout << "foo is instantiated" << endl; }
~foo() {}
void printmsg() final { cout << "msg from foo print" << endl; }
};
extern "C" __declspec(dllexport) foo* __cdecl Myfoo()
{
return new foo();
}
In the first method the pure virtual class bar is used as an interface, and it makes sense that its member function(s) is overridden by that in foo when the dll is loaded.
However, I found that foo doesn't have to be derived from bar, everything still works as long as foo has a Vtable:
In the second method, everything is the same except for the definition of foo:
#include <iostream>
#include <windows.h>
using namespace std;
class foo {
public:
foo() { cout << "foo is instantiated" << endl; }
virtual ~foo() {}
virtual void printmsg() final { cout << "msg from foo print" << endl; }
};
extern "C" __declspec(dllexport) foo* __cdecl Myfoo()
{
return new foo();
}
Could anyone please let me know why the second method works? I'm a bit confused because foo and bar are not related but the member function in bar can still be overridden.
So you cast a function returning foo* as a function returning bar* and then invoking it.
The end result is that you have a pointer to foo which is a pointer to an unrelated type bar. Using it in any way will lead to undefined behavior.
It appears to work in this specific case because the position of the printmsg virtual function in both vtables is the same, so invoking bar::printmsg on an instance of foo simply calls the "Nth entry in the vtable". If you add another virtual member to foo before printmsg, then it might get called instead (or the program might crash).
First example is very fragile because it implicitly relies on foo and bar being pointer-interchangeble.
Second example is broken because function Myfoo returns a pointer to class foo that is not related to bar and dereferencing it causes undefined behavior.
Function signature must match the function implemented in the dll. What you have right now is basically a wild reinterpret_cast from foo * to bar *.

When is a namespace::function() declaration useful?

Single File Example
Here is a simple program using namespaces.
#include <iostream>
namespace foo {
void hello();
}
void foo::hello() {
std::cout << "hello\n";
}
void foo::hello(); // Why is this syntax allowed? When is it useful?
int main() {
foo::hello();
}
This program compiles fine and produces the expected output.
$ ./a.out
hello
I want to know when is the void foo::hello(); declaration useful? In this program, clearly this declaration is redundant. But since this syntax exists, this must be useful in some other scenario?
Two-File Example
Here is an example that shows that the void foo::hello(); declaration standing alone is useless.
// foo.cpp
#include <iostream>
namespace foo {
void hello();
}
void foo::hello() {
std::cout << "foo::hello\n";
}
// main.cpp
void foo::hello(); // This does not work!
int main()
{
foo::hello();
}
Trying to compile the above two files leads to the following errors:
$ clang++ foo.cpp main.cpp
main.cpp:1:6: error: use of undeclared identifier 'foo'
void foo::hello();
^
main.cpp:5:5: error: use of undeclared identifier 'foo'
foo::hello();
^
2 errors generated.
The only way to fix main.cpp in the above example seems to be include the namespace declaration:
// main.cpp - fixed
namespace foo {
void hello();
}
void foo::hello(); // But now this is redundant again!
int main()
{
foo::hello();
}
So after we get this code to compile properly, the void foo::hello(); declaration seems redundant again. Is there any scenario where such a declaration would be playing a useful role?
In most cases in C++, for anything that can be either declared without defining it or can be completely defined, a declaration or a definition of that thing can appear in all the same contexts. So this is probably just a way of keeping the pattern consistent.
The C++ Standard does not go out of its way to forbid things that are a logical consequence of its other rules but just not useful, as long as it's reasonably clear what will happen if someone does it anyway. If it did add these restrictions, that would put extra work on compiler writers for no real benefit.
From [basic.def]/1
A declaration may introduce one or more names into a translation unit or redeclare names introduced by previous declarations. If so, the declaration specifies the interpretation and attributes of these names.
Which allows code like this
#include <iostream>
void foo();
void foo();
void foo();
void foo();
void foo();
int main()
{
foo();
}
void foo() { std::cout << "foo()"; }
To be valid. There is no harm in having multiple declarations of a function, as long as we have only one definition, it won't cause an issue.
Another example would be you have a global function you want to be a friend of multiple classes. You would include that function prototype in each class header so you can friend it and then you would include all of those class headers in your main source file. So
A.h
void foo();
struct A { friend void foo(); }
B.h
void foo();
struct B { friend void foo(); }
main.cpp
#include "A.h"
#include "B.h"
...
and that would be converted to
main.cpp
void foo();
struct A { friend void foo(); }
void foo();
struct B { friend void foo(); }
...
So we would want this to be legal.

Strange output with static objects

I can't understand what's happening...
Suppose that I have the following code:
// main.cpp
#include "some_header.h"
void bar();
int main()
{
foo();
bar();
}
// file.cpp
#include "some_header.h"
void bar()
{
foo();
}
// some_header.h
#include "foo.h"
inline
void foo()
{
static Foo instance;
}
// foo.h
#include <iostream>
class Foo
{
public:
Foo() { std::cout << "Foo::Foo() \n"; }
~Foo() { std::cout << "Foo::~Foo() \n"; }
};
Output
Foo::Foo()
Foo::~Foo()
The question is: why there's no second "Foo::Foo()" in the output? I think that it should be here because each translation unit (in my case main.cpp and file.cpp) should have its own Foo object (because of static keyword). Am I wrong? Can somebody quote the standard, please?
If i move the definition of Foo object from the function like this
// some_header.h
#include "foo.h"
static Foo instance;
inline
void foo()
{
}
the output will be
Foo::Foo()
Foo::Foo()
Foo::~Foo()
Foo::~Foo()
Is it inline magic or am I missing smth more fundamental?
What I need to do - I need to add boost::mutex object in some function for my header-only library to synchronize some WinAPI function calls like this:
inline
void some_func()
{
static boost::mutex sync;
boost::lock_guard<boost::mutex> lock(sync);
// Call some WinAPI function
}
How can I do it?
MSVC-11.0.
static is a heavily overloaded keyword in C++. At namespace scope, it means "entity has internal linkage, so every translation unit will have its own copy." At function scope, it means "there is only one such entity for the function and it persists across function calls."
So in your case, the funcion foo() simply has one object Foo instance with local scope, but global lifetime.
As for your mutex question, I can't see anything wrong with doing just what you posted in the question. some_func() will have a single instance of the mutex, and all calls to some_fucn() will share that one instance (and since C++11, it will be correctly and thread-safely initialised by the first such call). I'd say that's exactly what you need.

c++ namespace export

Is there a way in C++ to create an anonymous namespace, and only export a single function out of it?
I want something like:
namespace {
void Bar() {}
void Foo() { Bar(); }
}
Now, I want to somehow access to Foo() yet make sure there's no way to touch Bar()
Thanks!
If you want to export the function, you'll have to put it outside the anonymous namespace.
namespace {
void Bar() {};
};
void Foo() { Bar(); };
Since you want Foo() to have external linkage, you should declare it in a header file:
#ifndef FOO_H
#define FOO_H
void Foo();
#endif
Now everyone can see and call Foo()
But in Foo.cpp:
#include "Foo.h"
namespace {
void Bar(){ }
}
void Foo(){ Bar(); }
Now, as long as you control the source file Foo.cpp, no one can change access to Bar()
You could place them in different header files and make sure clients only get the header file that declares Foo(). However, you cannot implement Foo() inline with that solution.
why not
namespace {
void Bar() {};
};
void Foo() { Bar(); };
?
an anonymous namespace is accessible from the file you created it in
Define Bar as a global static function in the CPP file that contains the function body for Foo.
Edit: Its worth noting that this will only cause a link time error.
Edit2: And I ran a quick test and it seems you can't extern to an anonymous namespace.
Edit3:
Something like this would seem sensible (and lose the namespace)
static void Bar()
{
}
void Foo()
{
Bar();
}
You can now "extern void Foo();" but if you try the same with Bar then the linker will fail as Bar no longer has external linkage.