There generally exist two different kinds of functions.
One kind, that's static member functions, global functions, or global functions in a namespace. They do not reference or otherwise depend on members of a class instance. You can call these from one or another class, no problem.
The other kind is the (non-static) member function. It does in some way reference, access, change, use, or otherwise depend on something that is a class member. If you want to call such a function, you need the this
pointer.
When calling a function from "inside" the class itself, then this
is implicit. So, if you type e.g. bar()
inside A::abc
, then that's really this->bar()
, only without you needing to type that.
From "outside", that is e.g. in B::foo
, you will need to supply an object, or else the compiler has no way of knowing what data to operate on. It does not, and cannot work without.
So, you need to decide whether whatever happens in bar
depends on members of A
or not. If it does, you have no choice. Passing an object pointer (reference) is not about being inefficient, it's about "possible or not possible".
Otherwise, if there is maybe only some common functionality that is used by both B::foo
and A::bar
, in which case you could move that functionality to a (namespaced) global function or a non-capturing lambda, or anything the like.
You could thus for example call detail::blah()
from both B::foo
and A::bar
without needing to pass an object. That way, you would not need to duplicate code.
Or well, make A::bar
static, which will also work but in my opinion has no advantage, and is less clear (as it somehow makes the function a part of A
, logically, when in reality that's not truly the case).