I have a event based communication system, and this is the simplifed version of it:
class A: contains elements derived from class B
class B: has a pointer to its owner A
So when a B wants to communicate with other B-s, it calls A's Broadcast() method:
But I was wondering:
Pros:
Instead of m_owner->Broadcast() I can write just Broadcast()
Cons:
There will be +1 function calling in the procedure.
Is this a good practice? Why yes and why not?
In a situation that you have described, it probably indeed does not make much difference.
But in future you may find that you will need to add extra code to each place where Broadcast
is called, for example logging or mutex locking. In this case, a separate function will be really useful.
Also you mention that you have classes derived from B
. If this is a derived class that calls m_owner->Broadcast()
, and m_owner
is a base class field, then this is not a good pattern. Derived classes should better access parent's protected functions, not directly data members.