C++ Is there a way to work around circular dependency? - c++

Now I know that in C++ everything has to be declared before it can be used. But what if I have two functions that reference each other?
For example:
void func1() {
func2();
}
void func2() {
func1();
}
Is it completely impossible to do this?

A forward declaration is exactly what you want:
void func2(); // forward declare func2
void func1() {
func2();
}
void func2() {
func1();
}
The first void func2(); is called a forward declaration. You promise that you will define it according to this prototype eventually.

You need to forward declare func2() to be able to use it in func1():
void func2();
void func1() {
func2();
}
void func2() {
func1();
}
Now at the point where func1() references func2(), func2() has been declared, and at the point where func2() references func1(), func1() will have been declared.
However, calling either one of the two functions will cause an infinite loop, which will result in a stack overflow.

Is that snippet of code impossible without some sort of forward declaration? Yes. Think about it, when the compiler gets here:
void func1() {
func2();
}
He has never seen func2 before, and therefore can't compile it.
Most people create a .h file that contains function declarations so you can avoid this type of thing. For example,
foo.h
void func1();
void func2();
foo.c
#include "foo.h"
void func1() {
func2();
}
void func2() {
func1();
}

You should accept one of the other answers because that's how the language C++ works and there's nothing to do about it, if your concern is that writing lots of forwards is a pain, you should note that several frameworks already provide headers just for the sake of forward declaring stuff so that users don't have too.
This is for convenience when there's really a lot of stuff that is forward declared or there's stuff that need to be declared correctly (in example templates, aliases and also I saw some macro trickery once in a while).
Also generally you have to put declarations and definitions in different files to avoid recompiling where possible and generally to make the project more clear and manageable.
Functions.hpp
void func();
void func2();
Functions.cpp
#include "Functions.hpp"
void func(){
func2();
}
void func2(){
func();
}
user code:
main.cpp
#include "Functions.hpp"
int main(){
func();
return 0;
}
Also note that you have some confusion about "Declaration" and "Forward Declaration".
Actually when you put a function signature in your code your are Declaring it:
int function3(); // function declared
Forward declaration is about telling a class exists without telling anything more about its signature:
class myclass; //forward declaration
//possible declarations using "myclass" forward declaration
int function4(myclass & ref);
int function5(myclass * ref);
Forward declaration is used to keep headers simple and reducing compile time (a lot in certain cases) by moving unneeded details to implementation (.cpp) files.

You can simply place one function inside the other, then expressed as a (usually static) member function of a class, or as a lambda.
This assuming that the top-level calls from elsewhere are always to one of the functions.
Another possibility, with both functions available to the top-level calling code, is to place both functions as (most naturally static) members of a class, where they can be defined inline.
But I think it's more clean to just use the forward declaration.
There isn't really any good reason to avoid it, so a workaround like one of those mentioned above would just make other programmers waste some time scratching their heads – what on Earth is this for?
Amendment: example of the class scope approach:
struct Recursive
{
static void func1() { if( some_condition ) { func2(); } }
static void func2() { if( some_condition ) { func1(); } }
};
Example of the nested functions approach:
void func1()
{
const auto func2 = []{ if( some_condition ){ func1(); } }
if( some_condition ) { func2(); }
}

It's certainly possible with member functions. For example:
class A {
void func1() {
func2();
}
void func2() {
func1();
}
};
It can be more problematic if you need two classes to know about each other but does that answer your question?
Edit: You don't need the member function declarations before their definitions.

Related

Good practice to call a static function inside class or struct

I wonder what is the better practice to call a static function(and variables) inside a class or struct between A and B.
A: ClassName::functionName();
B: functionName();
Here's my simple example code:
In header file,
typedef struct _mystruct
{
static void myfunction();
} t_mystruct;
And in CPP file,
void t_mystruct::myfunction()
{
//do something
}
Now, in the same CPP file, what is the better practice to call this static function between A and B?
A: t_mystruct::myfunction();
B: myfunction();
Calling straight myfunction(); is only feasible if you are inside t_mystruct's implementation. In which case you can do according to your preferred coding style:
// .h
struct t_mystruct // You can declare it directly that way
{
static void myfunction();
void myOtherFunction();
};
// .cpp
void t_mystruct::myOtherFunction()
{
myfunction(); // That's fine!
t_mystruct::myfunction(); // That's fine too!
}
Otherwise, you have to explicitely use its fully qualified name:
void anywhereElse()
{
t_mystruct::myfunction(); // Mandatory
myfunction(); // Does not compile
}
This is true for your whole codebase, not only for the considered .cpp file.

Calling static methods in constructor

This seems a bit strange to me. Since a static method can have an instance of the class, one naturally expects that the compiler should not allow calling static methods inside the constructor. But I have tested the following code with every compiler and ironically, none of them gave me a single warning. Although in execution time they all throw exceptions. Am I missing something here?
#include <iostream>
class Foo
{
public:
inline Foo()
{
std::cout << "testing: var = " << bar() - 1 << '\n';
}
~Foo(){}
static int bar()
{
Foo f;
f.var = 10;
return f.test();
}
private:
int var;
int test()
{
return var + 1;
}
};
int main()
{
Foo foo;
return 0;
}
Live example
It is not illegal to call static functions from within the constructor. Only, you are getting a stack overflow, if you do it like you do. This results in
Foo() calls bar();
bar() calls Foo();
Foo() calls bar();
bar() calls Foo();
...
Until no stack is left.
This is exactly the same as if you had:
void f1();
void f2()
{
f1();
}
void f1()
{
f2();
}
int main(int, char*[])
{
f1();
return 0;
}
Only two global functions, nothing more. Would have been all the same in C, too (but you have do declare void f(void) there), or Java, C#, perl, python, ...
What warnings are you expecting? What you've written is an infinite recursion which has nothing to do with static member functions. You can do it with any other function inside or outside a class.
Static functions are not much different from the free ones. So free functions should also be banned from constructor? There is no point in forbidding to call static functions from constructors.
There is no reason not to call a static (or in fact a non-static) member function in a constructor (although it is not recommended to call virtual functions).

Is there a need to set up a class for one or several functions in C++

I feel confused with whether there is a need to set up a class for one or several functions. I give the following example to make my point clear:
file1.h
void Fun1();
void Fun2();
file1.cpp
void Fun1() {}
void Fun2() {}
As you can see we have two functions here, and people using these functions just need to include the header file and then call them. Then, I also have the choice of setting up a class without any member variables insider but only for these two functions (suppose these two functions are closely related):
file1.h
class Operation
{
Operation() {};
~Operation() {};
void Fun1();
void Fun2();
};
file1.cpp
void Operation::Fun1() {};
void Operation::Fun2() {};
Then my question is which practice is better and why. Thanks.
You should use a dedicated namespace
file1.h:
namespace MyDedicatedNameSpace
{
void Fun1();
void Fun2();
}
file1.cpp:
void MyDedicatedNameSpace::Fun1() {}
void MyDedicatedNameSpace::Fun2() {}
Or if you want to use a class, you should set these functions as static:
file1.h:
class Operation
{
public:
static void Fun1();
static void Fun2();
};
file1.cpp:
void Operation::Fun1() {};
void Operation::Fun2() {};
You don't "have to" put them in a class, you can go for both implementations. It's mostly a design preference. Java coders are used to putting those functions as static functions of a utility class, but in C++ you don't have to, although some people do.
If your concern is just encapsulation of those functions in a specific context, you might also consider putting them in namespaces.
There should be a reason you want to put them in one class.
If it's just for grouping, namespace better suits for this role.
file1.h
namespace Operation
{
void Fun1();
void Fun2();
};
file1.cpp
namespace Operation
{
void Fun1(){};
void Fun2(){};
};
P.S. If for some reason you would still prefer to use class, make functions static at least, so you wouldn't need to create an instance of this class.
file1.h
class Operation
{
public:
static void Fun1();
static void Fun2();
};
file1.cpp
void Operation::Fun1() {};
void Operation::Fun2() {};
Since you asked specifically about C++, the most correct answer would be to namespace them:
file1.h:
namespace MyNamespace
{
void Fun1();
void Fun2();
}
file1.cpp:
namespace MyNamespace
{
void Fun1() {}
void Fun2() {}
}
Then to use them you would simply call MyNamespace::Fun1() etc.
As I started out saying, this is most correct for C++.
If you were writing this for C, or mixed C/C++ it should be noted that C does not support namespaces. So in that case making them static functions of a class would be a better organizational route.
file1.h
class MyClass
{
public:
static void Fun1();
static void Fun2();
};
file1.c
void MyClass::Fun1() { }
void MyClass::Fun2() { }
NOTE: if you are doing mixed programming you should consider making it easier to include, but that's beyond the scope of this question.

Defining a function once that appears in multiple name spaces

I am trying to define a common interface to a set of functions and classes that will have multiple different backend implementations (Using different libraries).
As such I'd really rather, simply, define a function in one place and not in each separate namespace.
For example, I have a global function:
extern void Func();
Now I want to have 3 separate implementations of that function. One would be a straight C, One would be a hand coded assembler and one would be using library 'x'.
I am effectively trying to avoid doing the following:
namespace C
{
extern void Func();
}
namespace Asm
{
extern void Func();
}
namespace LibX
{
extern void Func();
}
Is there a good pattern to avoid doing this? When there are 100 odd functions it will become much more of a pain.
The only idea I can think of is to move all the definitions into a header file that has no header guards and then doing:
namespace C
{
#include "Functions.h"
}
namespace Asm
{
#include "Functions.h"
}
namespace LibX
{
#include "Functions.h"
}
Is there a better way of doing this that anyone can think of?
Make it a virtual function in an abstract base class. Implement it whenever you feel like it in a derived class.
class Foo{
public:
virtual void bar() const=0;
}
class FooASM:public Foo{
public:
virtual void bar() const{ ... }
}
etc.
I guess you want static polymorphism - means a template or a macro:
Template:
#include "C_Functions.h"
#include "Asm_Functions.h"
#include "LibX_Functions.h"
enum Namespace
{
NamespaceC,
NamespaceAsm,
NamespaceLibX
}
template <Namespace> Func();
template <> inline Func<NamespaceC>() { return C_Func(); }
template <> inline Func<NamespaceAsm>() { return Asm_Func(); }
template <> inline Func<NamespaceLibX>() { return LibX_Func(); }
const Namespace NSpace = ...
inline void f() {
Func<NSpace>()
}
An advantage is: You may have a common implementation for a specific function.
Similar you may do with macros (or you combine it)
I fear it ends up in #ifdef ... anyway, unless you try to have one lib for any hardware/system (which is pointless, in my view).

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.