given:
#include <stdio.h>
class A
{
friend class B;
private:
void func();
} GlobalA;
void A::func()
{
printf("A::func()");
}
class B
{
public:
void func();
};
void B::func()
{
GlobalA.func();
}
int main()
{
B b;
b.func();
getchar();
}
so really all B::func() does is call A::func(), is there a better way to do this? Or does the compiler just call A::func() directly when it compiles.
CONSTRAINTS:
class A creates threads and is used by multiple other classes. it is a global IO class to manage sockets/pipes, so i dont believe any type of inheritance would go over well.
NOTE: If this is a google-able problem please let me know as i did not what to search.
Check out the generated assembly from your compiler (I used GCC 4.7 -O3):
For
A::func()And
B::func():They’re identical – the compiler has done the smart thing for you for free behind the scenes. In this case your example was all in the same translation unit which makes it trivial for the compiler to decide if it’s worth doing like that. (There are cases where it wouldn’t be worth it most likely and the compiler will have a pretty good set of heuristics to help it figure out what’s best for any given target).
If they were in different translation units it becomes quite a lot harder to do. Some compilers will still manage the same optimisations but not all. You can of course ensure that it remains within the same translation unit for every case by defining functions like these as
inlinewhich lets you specify them in the header files.The moral of the story is don’t sweat over tiny details – writing code that makes sense and is maintainable is far more important.